Tuesday, 23 June 2015

Eclipse: Sample JUnit Test case Application

Sample JUnit Appliction in Eclipse

1.     Create a new project in Eclipse, let's say JUnitSample and setup the environment as mentioned in the previous post.
2.     Create a new Java class say Calc.Java under src.  This class has methods to perform the
      Arithmetic operations.
       Let’s create a method say add() which adds 2 numbers. It simply returns the sum of
       two integers.

package com.main.java;

public class Calc {

public int add(int number1, int number2)
{
return number1+number2;
}

}

3.      Now create a Junit Test case “CalcTest.Java” for the class “Calc”. select the class Calc and the method Add() while creating the JUnit test case in eclipse.

4.      Now you can see, there is a method added testAdd() with the annotation @Test.  The annotation signifies that the method will be run when we run the CalcTest test cases.

5.      Now let's add SetUp() method to predefine the values as shown in the example. Prefix it with @Before so that the method will be run before each test method runs.

6.      As you see in the below example, in the testAdd() method we are using assertTrue() method to check the value returned by add() method. It returns error, if the values doesn't match.

package com.main.java;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class CalcTest {

int checkValue;
int value1;
int value2;

@Before
public void setUp()
{
value1 = 5;
value2 = 8;
checkValue=13;
}

@Test
public void testAdd() {
assertTrue(checkValue==new Calc().add(value1, value2));
}

}

7.    Now we will see how to run the test case. Let's create TestRunner.Java.


As you see in the below example, in the main method, we are using JUnitCore.runClassses() method to run the CalcTest test cases. It will run all the methods inside the CalcTest.Java which are annotated with @Test.

The result will be stored in Result and using the methods getFailures() and wasSuccessful() to get the failures and status respectively. If executed with the above values the example should print "true".

package com.main.java;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {

public static void main(String args[])
{
Result result = JUnitCore.runClasses(CalcTest.class);
for(Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}

System.out.println(result.wasSuccessful());
}
}

Note:  You can run JUnit Testcases from the eclipse, simply by right clicking on the project -> Select Run AS -> select  JUnit Test. It will run all the test cases created.

No comments:

Post a Comment