Junit 4 Tutorial and example

  1. If you use Idea or Eclipse, The Junit IDE plug-in is normally included as a part of the IDE distribution.
  2. If do not using Idea or Eclipse, you can still use Junit as a standalone testing tool by downloading it from(http://www.junit.org).

Creating a Junit Test case

  1. Open the IDE, create a test project, if needed, please import the Junit library to your current project dependency libraries.
  2. Create a test class named SimpleTest and extends junit.framework.TestCase in the test project. In generic, the best practice is to define the test class name to start with ‘test’ and plus class name which need to be tested. (in case you use Junit4, it is no longer necessary to extend junit.framework.TestCase)
  3. Write a test method and assert desired results. If you use the Junit 3, you have to conventional define string ‘test’ as the prefix of test method, but in junit 4 or later, you can use annotation @Test to declare it, then Junit engine will explain it as a test method.
SimpleTest.java
package com.asjava;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;

/**
* Created by IntelliJ IDEA.
* User: asjava.com
*/
public class SimpleTest {

  @Test
  public void testEmptyCollection() {
    Collection collection = new ArrayList();
    assertNotNull(collection);
    assertTrue(collection.isEmpty());
  }
}

How do I Run The Test Case?

If you use Idea or Eclipse, just right-click in test method area of class editor and choose “run testEmptyCollection” option.

If you do not use IDE,  add a method ‘suite()’, it automatically creates a test suite including all test methods.

public static Test suite() {
  return new TestSuite(SimpleTest.class);
}

Then add a main method and use textui runner run all test cases.

public static void main(String args[]) {
  junit.textui.TestRunner.run(suite());
}

The ultimate step is to run this testcase.

java com.asjava.SimpleTest