The following code shows how to create a test case and verify the test case with JUnit.
Create a test case as follows.
A test case should be public class.
import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { @Test public void testAdd() { String str= "Junit is working fine"; assertEquals("Junit is working fine",str); } }
Then create the test runner
import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class Main { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
Click the Eclipse run button to run the test case.
The code above generates the following result.
In the Eclipse we can choose to run the Test case itself without using a main class.
Just right click the Test case Java source file and choose the Run as JUnit Text