JUnit
This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. (November 2008) |
Developer(s) | Kent Beck, Erich Gamma, David Saff |
---|---|
Stable release | 4.7
/ August 4, 2009 |
Repository | |
Written in | Java |
Operating system | Cross-platform |
Type | Unit testing tool |
License | Common Public License |
Website | http://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
- JTiger, an alternative to JUnit
- Mock object
- TestNG, an alternative to JUnit
- djUnit, performs test of JUnit