Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
  }
}
like image 696
Vampire Slayer Avatar asked Dec 18 '25 02:12

Vampire Slayer


1 Answers

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.

like image 196
Ashish Patil Avatar answered Dec 20 '25 15:12

Ashish Patil