1.
Let’s create the class Calc.Java whose methods need to be tested. It has two methods add
and subtract which will do the simple addition and subtraction of 2 numbers.
package com.main.java;
public class Calc {
public int add(int number1, int number2)
{
return number1+number2;
}
public int subtract(int number1, int number2)
{
return number1-number2;
}
}
2.
Let’s Create CalcTest.java to test the add() method of Calc.java
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));
}
}
3.
Let’s create another Test class CalcTest1.java to test the subtract()
method of the Calc.java
package com.main.java;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CalcTest1 {
int value1;
int value2;
@Before
public void setUp()
{
value1 = 8;
value2 = 5;
}
@Test
public void testSubtract() {
assertTrue(3==new Calc().subtract(value1, value2));
}
}
4.
Now create a JUnit Test Suite in eclipse, by
clicking on File-> New -> Other -> JUnit Test Suite. Select the test
classes to be included in the Test Suite as shown below in the screen shot.
Note: Make sure to select the New JUnit 4 Suite on
top otherwise the test classes won’t be displayed for selecting.
5.
As you can see, it has created the TestSuit with
the name AllTests with the 2 annotations. The annotations @SuiteClasses
and @RunWith are required for
running the class as TestSuite.
In the @SuiteClasses annotation, both the test classes selected above are populated.
package com.main.java;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@SuiteClasses({ CalcTest.class, CalcTest1.class })
public class AllTests {
}
6. In
the TestRunner.Java class file, give
the TestSuite name i.e AllTests in the JUnitCore
RunClasses() method. It will run
both the test case classes mentioned above.
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(AllTests.class);
for(Failure failure :
result.getFailures())
{
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}