2. Debugging single java class with JUnit

Debugging single java class with JUnit

– The Great thing About JUnit is I can debug every line of my Code, Without run the whole of my application such as Ear file into Server.

After I successfully setting the BuildPath for Junit jar.

1. Create a Simple java program – LoopCount.java and testcase.java from this page Example :

2. Add the breakpoint on left side of the code that we would like to start debugging:

breakpoint

3. Then we click to debug mode.

debug

4.  Right click , Debug As JUnit Test.

debugUnitTest

 

5. Press button keyboard F6 , to go trough line by line of the codes. F8 to end of debugging or to start to next breakpoint. (In Eclipse)

 

1. How To Write JUnit Test in Eclipse – JUnit

What is JUnit?

  • JUnit is a simple framework to write repeatable test, which is use as a testing framework for the java programming Language.
  • The purpose of JUnit is to writing & running test cases for java programs.

Why I need it for my Unit Testing , when I write a java program?

  •  The best thing about JUnit testing is , when I have been assigned a task to change some small logic , I doesn’t need to start the server in debugging mode to do the test Unit.

Where to Start?

1. Get the JUnit Jar – junit-4.10.jar
2. Using Eclipse (Java IDE)
3. Setup an Example JUnit Project.

junit2

– Above is the example, create a package – unit.test.fndong.junit

4.Create a lib folder which we will put the jar file for JUnit.

junit3

4.  I have create a example java program – LoopCount.java:

package unit.test.fndong.junit;
public class LoopCount { /*
* Variable (integer – i) will loop until how many number variable number1 value have.
* Then( integer – i ) will add with number2 then return the total of sum i and number2.
*
*
*/
private int total;
private int i =0;
// add calculate method
public int addCalculate(int number1, int number2){
// using do while loop
do{
System.out.println(“” + i);
}while(i < number1);
total = number1 + number2;
return total;
}
}

5. then we create the important class java for running the unit test. Create – testcase.java

packageunit.test.fndong.junit;
// import the junit jar
import static org.junit.Assert.*;
import unit.test.junit.JUnitExample;
import org.junit.Test;
public class testcase {
@Test
public void loopCalculation(){
LoopCount loopcount = new LoopCount();
// using assertEquals method
assertEquals(5, loopcount.addCalculate(3,3));
}
}

6. To Test our method on JUnit Test, right click on – testcase.java , choose – Run As > JUnit Test

junit4
7. When I wrongly put the value of number1 in testcase by calling method addCalculate from class LoopCount for line below:
– The true value is – 5, but I wrongly put value number1 to 3
assertEquals(5, loopcount.addCalculate(3,3));

junit5

– Result is , your Ecliple will show error message.
8. Lastly we try to make the result is correct which the count value supposedly 5.
– Put the correct number1 to 2

junit6