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.


– 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.


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
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

// import the junit jar
import static org.junit.Assert.*;
import unit.test.junit.JUnitExample;
import org.junit.Test;
public class testcase {
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

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


– 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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s