Jump to content

JUnit

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 62.232.250.50 (talk) at 12:54, 25 November 2009. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

JUnit
Developer(s)Kent Beck, Erich Gamma, David Saff
Stable release
4.7 / August 4, 2009 (2009-08-04)
Repository
Written inJava
Operating systemCross-platform
TypeUnit testing tool
LicenseCommon Public License
Websitehttp://junit.org

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with SUnit.

JUnit has been ported to other languages including Ada (AUnit), PHP (PHPUnit), C# (NUnit), Python (PyUnit), Fortran (fUnit), Delphi (DUnit), Free Pascal (FPCUnit), Perl (Test::Class and Test::Unit), C++ (CPPUnit), and JavaScript (JSUnit).

JUnit is linked as a JAR at compile-time; the framework resides under packages junit.framework for JUnit 3.8 and earlier and under org.junit for JUnit 4 and later.

Examples

JUnit 3.8

A simple example for a test-case in JUnit 3.8 and earlier could be as follows:

import junit.framework.*;

public class MultiplicationTest extends TestCase {
  /** Test whether 3 * 2 = 6, according to the JVM. */
  public void testMultiplication() {
    assertEquals("Multiplication", 6, 3 * 2);
  }
}

(Compare with the similar example for Mauve.)

The method testMultiplication will be discovered automatically by reflection.

JUnit 4.0

Translating this above example into JUnit 4.0 results in:

import org.junit.*;
import static org.junit.Assert.*;

public class MultiplicationTest {
  /** Test whether 3 * 2 = 6, according to the JVM. */
  @Test
  public void testMultiplication() {
    assertEquals("Multiplication", 6, 3 * 2);
  }
}

The method testMultiplication will be discovered automatically by its Test Annotation (a feature of Java 5) without regard to its name. It offers a fundamental test using only the JUnit framework and the core of the JVM and language.

There are, however, several issues to consider here. JUnit is not a programming language; this trivial example does not demonstrate the power of JUnit. It is conventional to see test case classes named as the class being tested, appended with "Test". Also, something more meaningful is usually printed in the assertion message, as in the following:

Assert.assertEquals("Test whether 2 * 2 = 4", 4, Multiplier.multiply(2, 2));

See also