Java JUnit Tutorial - JUnit HelloWorld

The following code shows how to create a test case and verify the test case with JUnit.

Test Case

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 {
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);

Test Runner

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()) {

Run the test case

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