Wednesday, July 31, 2013

Test Driven Development example - Part 3 (Simple Unit Testing for Java with NetBeans)

Our 2nd task in the to do list is,
[2] getFibonacci(1) ==> 1
now we have a passing code.
we have to make it fail. to that we can ask it the 1st Fibonacci number.
change the FibonacciTest.java file as below.
Here i have introduced a new method for check the result for input 1. Then it will be easy to identify what is going on.

 
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;

public class FibonacciTest {

    @Test
    public void testGetFibonacci_0() {
        int x = 0;
        Fibonacci instance = new Fibonacci();
        int expResult = 0;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
    @Test
    public void testGetFibonacci_1() {
        int x = 1;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
}


Then run the code and see the result. You will see that our first test will pass and the second one is failing. That is because the getFibonacci method only return value '0' for any input.
So our test is failing. And now we have a failing code. :)

Lets make it pass. To do that we have to edit the getFibonacci method to correctly return the first 2 Fibonacci numbers.
Do the following changes in Fibonacci.java file
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1) {
            result = 1;
        }
        return result;
    }
}

Run the test file and see the results.

seems it is working :)
our second task is done. lets look at our to do list :)

[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8


lets move to our next task
[3] getFibonacci(2) ==> 1
and again we have a passing code. we have to make it fail. when we pass the '2' as input it will fail. make another testing method to do it.
 
 
 @Test
    public void testGetFibonacci_2() {
        int x = 2;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }


result will be looks like

ok our 3rd test is failing. :) lets make it pass. we have to correctly produce first 3 Fibonacci numbers to that.
Edit the Fibonacci.java like below
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        }
        return result;
    }
}


and the result will be

So we have completed our 3rd task also. :)
we can use if else and do that for any input. A brute force method. But after some time we may able to identify a pattern of the inputs and the out puts.

0 comments:

Post a Comment