'How to use unit testing if there are multiple outputs in java?
How can I test a class that returns the Fibonacci series? I used an iterator for this code. The FibonacciIteratorTest class is below.
public class FibonacciIterator implements Iterator<Integer>, Iterable<Integer>{
private int num1;
private int num2;
private int num3;
private int count;
private int to;
public FibonacciIterator(int to){
this.num1 = 0;
this.num2 = 1;
this.to = to;
this.count = -1;
}
public static Iterable<Integer> to(int num){
return new FibonacciIterator(num);
}
@Override
public Iterator<Integer> iterator(){
return this;
}
@Override
public boolean hasNext(){
if(count < to){
count++;
return true;
}
return false;
}
@Override
public Integer next(){
if(count < 2){
return count;
}
num3 = num1 + num2;
num1=num2;
num2=num3;
return num3;
}
}
Instead of 55, the expected values should be 0 1 1 2 3 5 8 13 21 34 55.
class FibonacciIteratorTest {
@Test
void shouldReturnFibonacciNumbers(){
FibonacciIterator fibonacciNumbers= new FibonacciIterator();
assertEquals(55,fibonacciNumbers.to());
}
}
Solution 1:[1]
Considering your fibonacciNumbers.to
method returning int []
then you might want to use assertArrayEquals:
int arr[]={0,1,1,2,3,5,8,13,21,34};
assertArrayEquals(arr, fibonacciNumbers.to(10));
If your method fibonacciNumbers.to()
returns other than int array, then please tell us, so that answer can be changed accordingly.
Solution 2:[2]
Assuming your FibonacciIterator.to(int)
method returns an Iterator<Integer>
:
@Test
void shouldReturnFibonacciNumbers(){
var groundTruth = new ArrayList(Arrays.asList(1,1,2,3,5,8,13,21,34,55)).iterator();
var fibonacciNumbers = new FibonacciIterator().to(10);
while(groundTruth.hasNext()){
if(!fibonacciNumbers.hasNext()){
fail("Length doesn't match");
}
assertEquals(groundTruth.next(), fibonacciNumbers.next());
}
}
I didn't test the code, but it should at least be close to working.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ashish Patil |
Solution 2 | Kenny |