Junit 4 Tutorial and Example – Get Starting

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

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

  1. Randall Stewart

    A printable version would be nice. There’s too much info on these pages to absorb in one sitting. There’s too much advertising and other crap (like the HUGE fixed “Back to top” button) to print the page out efficiently. If the advertising agreements don’t allow you to provide a printable version . . . well, I guess that’s the price I’ll have to pay for having free access to this info. It’s good info, though.

    Reply
    1. admin author

      Thanks, I will try to improve the page that to be less useless content, but, you know, a few advertisement have to be here because the cost pay for domain, server and so on.

      Reply