http://www.tutorialspoint.com/junit/junit_quick_guide.htm
Create Test Case Classes
Create a java class file name TestJunit1.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit1 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); assertEquals(message, messageUtil.printMessage()); } }
Create a java class file name TestJunit2.java in C:\ > JUNIT_WORKSPACE
import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public class TestJunit2 { String message = "Robert"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Robert"; assertEquals(message,messageUtil.salutationMessage()); } }
Create Test Suite Class
- Create a java class.
- Attach @RunWith(Suite.class) Annotation with class.
- Add reference to Junit test classes using @Suite.SuiteClasses annotation
Create a java class file name TestSuite.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestJunit1.class, TestJunit2.class }) public class JunitTestSuite { }
Create Test Runner Class
Create a java class file name TestRunner.java in C:\ > JUNIT_WORKSPACE to execute Test case(s)
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(JunitTestSuite.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
Compile all java classes using javac
C:\JUNIT_WORKSPACE>javac TestJunit1.java TestJunit2.java JunitTestSuite.java TestRunner.java
Now run the Test Runner which will run test case defined in provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
Robert Inside testSalutationMessage() Hi Robert true