Home > Enterprise >  How to use Unit Testing if there are multiple Outputs in java?
How to use Unit Testing if there are multiple Outputs in java?

Time:05-11

How can i Test a class, that returns fibonacci series? I used an iterator for this code. The FibonacciIteratorTest class is bellow. thank you in Advance .

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 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());
  }
}

Thanks to your suggestions, i solved it. This is how it looks now. May can help future readers.

class FibonacciIteratorTest {
    @Test
    void shouldReturnFibonacciNumbers(){
        var groundTruth = new ArrayList(Arrays.asList(0,1,1,2,3,5,8,13,21,34,55)).iterator();
        FibonacciIterator fibonacciNumbers= new FibonacciIterator(10);
        while(groundTruth.hasNext()){
            if(!fibonacciNumbers.hasNext()){
                fail("Length doesn't match");
            }
            assertEquals(groundTruth.next(), fibonacciNumbers.next());
        }
    }
}

CodePudding user response:

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.

CodePudding user response:

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.

  • Related