After following the previous work now we are good to code :)
First of all lets edit the Fibonacci.java file. lets add a new method.
package tdd; public class Fibonacci { public void getFibonacci(int x) { } }Now edit the FibonacciTest.java file like below.
package tdd; import org.junit.Test; import static org.junit.Assert.*; public class FibonacciTest { public FibonacciTest() { } @Test public void testGetFibonacci() { fail("The test case is a prototype."); } }now just right click on the FibonacciTest.java file and run it.
The result will be as below.
Ok now we have a failing code :) We have to make it pass now.
lets make a 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
case 1) we have to generate the first Fibonacci number. now we have a failing code. lets make it pass and return the correct answer (0) for input (0)
change the Fibonacci.java files getFibonacci method as follows. So that it return the correct answer to the input '0'. If you remember the 3rd point it says that "we are not allowed to write any more production code than is sufficient to pass the one failing unit test" . so we have a failing test case. We have to write the code only to pass that failing code.
package tdd; public class Fibonacci { public int getFibonacci(int x) { return 0; } }
Then change the FibonacciTest.java file as below.
package tdd; import org.junit.Test; import static org.junit.Assert.*; public class FibonacciTest { public FibonacciTest() { } @Test public void testGetFibonacci() { //fail("The test case is a prototype."); // this is the xth fibonacci number int x = 0; //make an instance of the Fibonacci class to access //getFibonacci method Fibonacci instance = new Fibonacci(); // this is our expected result int expResult = 0; // get the actual result int result = instance.getFibonacci(x); // this will check and compare the result and the // expected result. If both match test will pass. assertEquals(expResult, result); } }
The comments will help you to understand what is going on. :)
lets run the code and see
wow we have just made our failing test case passed. :)
Our code will correctly return the 0th Fibonacci number (lets use the 0th indexing)
our first task in the to do list is done :)
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8
way to go :)
0 comments:
Post a Comment