How to return value from unit test? - return

I have the following problem.I have a process that is done in 3 steps:
Step 1 -> Step 2 ->Step 3
I want to be able to test all combinations.
Step1
Step1+Step2
Step2
Step2+Step3
Step1+Step2+Step3
In order to do this i would like to be able to return something from each of my Unit Tests.
I do not want to create global variables and mutate them every single time.
class TestPipeline
{
[Testcase]
public Int Step1()
{
////do something
Int outputStep1=doSomeStuff();
return outputStep1;
}
[Testcase]
public Int Step2()
{
Int inputStep1=Step1();
Int outputStep2=doSomething(inputStep1);
return outputStep2;
}
[Testcase]
public void Step3()
{
Int inputStep2=Step2();
Int result=doSomethingElse(inputStep2);
}
}
How can this be done ?

It sounds to me that you need helper methods that you can reuse, you're most of the way there, just need to extract out the methods.
As for getting the combinations correct I'd just hard-code the combinations. It looks like your steps are sequential so there won't be such a test as Step2+Step3 because it would really be Step1+Step2+Step3.
Tests are normally data driven and having logic in the test to vary behaviour based on data with something such as Combinatorial adds unwanted logic into the test.
class TestPipeline
{
private int doSomeStuff()
{
return someStuff;
}
private int doSomething(int someStuff)
{
return something;
}
private int doSomethingElse(int something)
{
return somethingElse;
}
[Testcase]
public void Step1()
{
////do something
int outputStep1 = doSomeStuff();
return outputStep1;
}
[Testcase]
public void Step1Step2()
{
int inputStep1 = doSomeStuff();
int outputStep2 = doSomething(inputStep1);
return outputStep2;
}
[Testcase]
public void Step1Step2Step3()
{
int inputStep1 = doSomeStuff();
int outputStep2 = doSomething(inputStep1);
int result = doSomethingElse(inputStep2);
}
}

Related

Reusing signal handlers?

Is there a way in Vala to have multiple signal handlers perform the same code, while they have access to the local scope?
Defining a lambda using a delegate works, but requires a delegate definition and gives the warning "copying delegates is not supported":
delegate void ChangeHandler ();
void test () {
var answer = 42;
ChangeHandler handler = () => {
debug("size or position changed. answer: %i", answer);
};
size_changed.connect (handler);
position_changed.connect (handler);
}
As far as I know there is also no way to pass information to handlers? something like:
void test () {
var answer = 42;
size_changed.connect (handler, answer);
position_changed.connect (handler, answer);
}
void handler (answer) {
debug("size or position changed. answer: %i", answer);
}
I could do this, but this requires a lot of extra code, especially when there are many arguments.
void test () {
var answer = 42;
size_changed.connect (handler, answer);
position_changed.connect (() => handler(answer));
}
void handler (answer) {
debug("size or position changed. answer: %i", answer);
}
Is there a way to connect multiple signals to one anonymous function? Something like:
void test () {
var answer = 42;
multi_connect(size_changed, position_changed, () => {
debug("size or position changed. answer: %i", answer);
});
}
How about using this to pass data:
public class Test : GLib.Object {
public signal void sig_1 ();
public signal void sig_2 ();
private int answer = 42;
private void sig_handler (Test t) {
stdout.printf("sig_1 or sig_2 triggered. answer: %d\n", answer);
}
public static int main(string[] args) {
Test t1 = new Test();
t1.sig_1.connect(t1.sig_handler);
t1.sig_2.connect(t1.sig_handler);
t1.sig_1();
t1.sig_2();
return 0;
}
}
Maybe it is more readable with two classes:
public class SignalRaiser : GLib.Object {
public signal void sig_1 ();
public signal void sig_2 ();
}
public class SignalReceiver : GLib.Object {
private int answer = 42;
public void sig_handler (SignalRaiser sender) {
stdout.printf("sig_1 or sig_2 triggered. answer: %d\n", answer);
}
}
int main(string[] args) {
var raiser = new SignalRaiser();
var receiver = new SignalReceiver();
raiser.sig_1.connect(receiver.sig_handler);
raiser.sig_2.connect(receiver.sig_handler);
raiser.sig_1();
raiser.sig_2();
return 0;
}

Writing a size() method for a User-defined Stack Class

I'm writing a program that requires the length/size of a stack. Because I am not importing the Stack class (and I've made my own - see below) I don't know how to make a method that calculates the size of the stack and returns that integer value. Here's the Stack class so far:
public class Stack<String> implements StackInter<String>
{
public void push(String x)
{ // This method is written
}
public String pop()
{ // This method is written
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
// What goes in here!
}
}
This is where I want to use the size method
public class InfixCalculator
{
Stack<String> stack = new Stack<String>();
int size = stack.size();
}
Any suggestions would be greatly appreciated!
the pseudo code is somthing like this:
public class Stack<String> implements StackInter<String>
{
private size;
//constructor
public Stack<String>(){
size=0;
}
public void push(String x)
{ // This method is written
size++;
}
public String pop()
{ // This method is written
if(size > 0 )
size--;
}
public boolean isEmptyStack()
{ // This method is written
}
public String peek()
{ // This method is written
}
public int size()
{
int theSize=size;
return theSize;
}
}
after you apply your operations the size can be computed.
If your Stack is an array write
public int size() {
return array.length;
}

How to sort Vectors in blackberry using SimpleSortingVector?

I am having trouble to sort Vector for my blackberry app using SimpleSortingVector. My stuff does not sort it remains the same.
here is what i have so far...
MyComparator class
private Vector vector = new Vector(); //Assume that this vector is populated with elements already
SimpleSortingVector ssv = new SimpleSortingVector();
ssv.setSortComparator(new Comparator() {
public int compare(Object o1, Object o2) {
Record o1C = (Record)o1;
Record o2C = (Record)o2;
return o1C.getName().compareTo(o2C.getName());
}
public boolean equals(Object obj) {
return compare(this, obj) == 0;
}
});
for(int i=0;i<vector.size();i++){
Record record = new Record();
record=(Record) vector.elementAt(i);
//when you add elements to this vector, it is to post to be automatically sorted
ssv.addElement(record);
}
class Record
public class Record {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
SimpleSortingVector does not sort by default. This was unexpected for me the first time I ran into it, too, given the name of the class.
You can do one of two things. Call SimpleSortingVector.setSort(true) to make sure the vector is always sorted after each change. This is surprisingly not turned on by default.
Or, you can call SimpleSortingVector.reSort() after adding all the elements to the vector, to do the sort in one batch operation.

a last in, first out (LIFO) abstract data type and data structure. Perhaps the most common use of stacks is to store

MyStack()
{
Vector<Integer> v=new Vector<Integer>(10,2);
}
void push(int n)
{
v.addElement(n);
}
void pop()
{
if(v.isEmpty())
System.out.println("Stack underflow!");
else
System.out.println(v.elementAt(0));
}
void display()
{
for(int i=0;i<v.size();i++)
System.out.print(v.elementAt(i) +" ");
}
}
class StackDemo
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
MyStack s=new MyStack();
int option=0;
do
{
System.out.println("1: Push\n2:Pop\n3:Display\n4:Quit");
System.out.println("Enter your option: ");
option=in.nextInt();
switch(option)
{
case 1:
{
System.out.println("Enter an integer:");
int n=in.nextInt();
s.push(n);break;
}
case 2:s.pop();break;
case 3:s.display();break;
}
}
while(option!=4);
}
}
// throws an error: variable v not found. Any help would be much appreciated.Thanks.
It looks like v is being created locally in your constructor instead of as a member of your class.
Try defining v as a class member and then simply assign it in your constructor.
class MyStack {
Vector<Integer> v;
public MyStack() {
v = new Vector<Integer>(10,2);
}
}
Or just assign it when you define it:
class MyStack {
Vector<Integer> v = new Vector<Integer>(10,2);
}
Check out the Java tutorial on class members.

db4o Tranparent Persistence doesn't store later objects in my own ActivatableCollection<T>

I'm rolling my own ActivatableCollection<T> for db4o but cribbing heavily from the builtin ActivatableList<T> implementation. I'm running into the problem where transparent persistence doesn't seem to be working correctly. In the test code below:
[Fact]
void CanStoreActivatableCollection()
{
var planets = new ActivatableCollection<Planet>();
var pagingMemoryStorage = new PagingMemoryStorage();
var config = Db4oEmbedded.NewConfiguration();
config.Common.Add(new TransparentActivationSupport());
config.Common.Add(new TransparentPersistenceSupport());
config.File.Storage = pagingMemoryStorage;
var objectContainer = Db4oEmbedded.OpenFile(config, "Memory.yap");
planets.Add(new Planet("Mercury"));
objectContainer.Store(planets);
planets.Add(new Planet("Venus"));
planets.Add(new Planet("Earth"));
objectContainer.Commit();
objectContainer.Close();
config = Db4oEmbedded.NewConfiguration();
config.Common.Add(new TransparentActivationSupport());
config.Common.Add(new TransparentPersistenceSupport());
config.File.Storage = pagingMemoryStorage;
objectContainer = Db4oEmbedded.OpenFile(config, "Memory.yap");
planets = objectContainer.Query<ActivatableCollection<Planet>>().FirstOrDefault();
Assert.NotNull(planets);
Assert.Equal(3, planets.Count);
objectContainer.Close();
}
The planet "Mercury" is stored, but not "Venus" and "Earth". If I change from ActivatableCollection to ActivatableList, then all 3 planets are stored.
What am I missing? My ActivatableCollection is just minimal implementation of ActivatableList as best as I can tell.
Below is my implementation of ActivatableCollection:
public class ActivatableCollection<T>
: ICollection<T>
, IActivatable
, INotifyCollectionChanged
{
List<T> _list;
List<T> List
{
get
{
if (_list == null)
_list = new List<T>();
return _list;
}
}
public ActivatableCollection()
{
}
public int Count
{
get
{
ActivateForRead();
return List.Count;
}
}
public bool IsReadOnly
{
get
{
ActivateForRead();
return ((IList) List).IsReadOnly;
}
}
public void Add(T t)
{
ActivateForWrite();
List.Add(t);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t));
}
public void Clear()
{
ActivateForWrite();
List.Clear();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public bool Contains(T t)
{
ActivateForRead();
return List.Contains(t);
}
public void CopyTo(T[] array, int index)
{
ActivateForRead();
List.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
ActivateForRead();
return List.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Remove(T t)
{
ActivateForWrite();
bool removed = List.Remove(t);
if (removed)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t));
return removed;
}
[Transient]
private IActivator _activator;
public virtual void Bind(IActivator activator)
{
if (_activator == activator)
return;
if (activator != null && _activator != null)
throw new InvalidOperationException();
_activator = activator;
}
public virtual void Activate(ActivationPurpose purpose)
{
if (_activator == null)
return;
_activator.Activate(purpose);
}
protected virtual void ActivateForRead()
{
Activate(ActivationPurpose.Read);
}
protected virtual void ActivateForWrite()
{
Activate(ActivationPurpose.Write);
}
[Transient]
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
}
I've also tried copying the code from GenericTypeHandlerPredicate and registering my ActivatableCollection to use the GenericCollectionTypeHandler. That results in a crash in GenericTypeFor() throwing an InvalidOperationException() when "Mercury" is being stored.
Just want to mention my answers from the db4o forums also here, for people with a similar problem:
First part of the issue:
From db4o's point of view nothing has changed in the 'ActivatableCollection' object and therefore no changes are stored. This is what is happening:
When you add the items, the ActivatableCollection is marked as changed.
When you commit the changes are stored. However the ' ActivatableCollection' holds the reference to the same object. db4o only stores the changes in the ActivatableCollection-object, which is the reference to the List. Since it is the same, no actual change is stored.
The List of the ActivatableCollection is never updated, because it wasn't marked as 'changed'
So the transparent activation doesn't see the changes in the list. You can fix your issue simply by using an ActivatableList in you're ActivatableCollection implementation. Just change the List with a IList interface and instantiate a ActivatableList instead of an List.
The second part of the issue: Why doesn't it work even when registering the GenericCollectionTypeHandler for this type? Here we hit a implementation detail. The GenericCollectionTypeHandler has an internal list of supported types, which doesn't include the self made 'ActivatableCollection'. GenericCollectionTypeHandler is not really part of the public API and intendet for internal use only.
Workaround / Fix
Just use an ActivatableList<T> instead of a List<T>. then everything works fine.

Resources