Programming Search⌘K

Toolcore

JUnit

Also called JUnit 4, JUnit 3.

JUnit is the main test framework of Java and the first widely known xUnit framework. This page follows it from the TestCase classes of JUnit 3 to the runners and rules of JUnit 4.

Role
test-framework
Licence
epl-2.0
Home page
junit.org

What it is

JUnit is the main Test framework of Java. The JUnit 4 site describes it so: "JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks."1 The FAQ lists its parts: "Assertions for testing expected results", "Test fixtures for sharing common test data" and "Test runners for running tests".2 It also says: "JUnit was originally written by Erich Gamma and Kent Beck."2

The name covers several generations with different models:

  • JUnit 3 and earlier: a test class extends junit.framework.TestCase, and each method whose name starts with test is a test.34
  • JUnit 4: annotations such as @Test and @Before mark the tests, @RunWith picks a runner, and @Rule wraps tests in extra behaviour.567
  • JUnit 5 and JUnit 6: a launcher platform with test engines, the Jupiter programming model and one extension API. See JUnit 5.

This page covers the product, the JUnit 3 and JUnit 4 models, and the versions. The examples run JUnit 4.13.2 on the JUnit Platform, through the Vintage engine.8

Install and first use

JUnit 4 is the jar junit:junit. The last version is 4.13.2.9 In a Maven pom.xml:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
  <scope>test</scope>
</dependency>

A Gradle build that runs JUnit 4 tests on the JUnit Platform adds junit:junit:4.13.2 and the engine org.junit.vintage:junit-vintage-engine.10 JUnit 4 also has its own console runner: java org.junit.runner.JUnitCore followed by the names of the test classes.5

The cookbook gives the steps for a JUnit 4 test: "Annotate a method with @org.junit.Test", and for a fixture, "Annotate a method with @org.junit.Before and initialize the variables in that method".5

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import java.util.ArrayDeque;
import java.util.Deque;
import org.junit.Before;
import org.junit.Test;

public class PlaylistTest {
    static final class Playlist {
        private final Deque<String> songs = new ArrayDeque<>();

        void add(String song) {
            songs.addLast(song);
        }

        String next() {
            String song = songs.pollFirst();
            if (song == null) {
                throw new IllegalStateException("the playlist is empty");
            }
            return song;
        }
    }

    private Playlist playlist;

    @Before
    public void setUp() {
        playlist = new Playlist();
        playlist.add("Intro");
    }

    @Test
    public void nextReturnsSongsInOrder() {
        playlist.add("Outro");
        assertEquals("Intro", playlist.next());
        assertEquals("Outro", playlist.next());
    }

    @Test
    public void nextOnEmptyPlaylistFails() {
        playlist.next();
        assertThrows(IllegalStateException.class, () -> playlist.next());
    }

    @Test(expected = IllegalStateException.class)
    public void theOlderWayToExpectAnException() {
        playlist.next();
        playlist.next();
    }
}
Output
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
   └─ PlaylistTest ✔
      ├─ theOlderWayToExpectAnException ✔
      ├─ nextOnEmptyPlaylistFails ✔
      └─ nextReturnsSongsInOrder ✔

Test run finished after $TIME
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         3 tests found           ]
[         0 tests skipped         ]
[         3 tests started         ]
[         0 tests aborted         ]
[         3 tests successful      ]
[         0 tests failed          ]

The report shows the class under the JUnit Vintage engine. assertThrows came in JUnit 4.13.11 Before it, a test gave the class of the exception in @Test(expected = ...), as the last test does.5 That form passes when any line of the method throws the exception, so it can hide an exception from the wrong line.

Concepts of the tool

JUnit 3: a base class and a naming rule

In JUnit 3, the comment of TestCase gives the steps: "implement a subclass of TestCase", "define instance variables that store the state of the fixture", "initialize the fixture state by overriding setUp()" and "clean-up after a test by overriding tearDown()."3 The comment also says: "Each test runs in its own fixture so there can be no side effects among test runs."3 A TestSuite made from a class "Adds all the methods starting with "test" as test cases to the suite."4 So the name of a method decides if it is a test.

JUnit 4.13.2 still contains junit.framework, so a JUnit 3 test still runs:

import junit.framework.TestCase;

public class TallyTest extends TestCase {
    private StringBuilder tally;

    @Override
    protected void setUp() {
        tally = new StringBuilder();
    }

    public void testStartsEmpty() {
        assertEquals("", tally.toString());
    }

    public void testMarksAddUp() {
        tally.append("||");
        tally.append("|");
        assertEquals(3, tally.length());
    }

    // The name does not start with "test", so JUnit 3 does not run this method.
    public void checkNothing() {
        fail("this method is not a test");
    }
}
Output
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
   └─ TallyTest ✔
      ├─ testStartsEmpty ✔
      └─ testMarksAddUp ✔

Test run finished after $TIME
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

The method checkNothing would fail, but it is not in the report, because it is not a test. A typo in the prefix, such as tset, has the same effect: the test does not run, and nothing tells you.

In JUnit 3 and JUnit 4, the optional message of an assertion is the first argument, as in assertEquals("wrong total", 3, total). Martin Fowler remembers this choice of Beck and Gamma as a break with the Java convention of optional arguments at the end.12 Jupiter moved the message to the last argument.8

JUnit 4: annotations, runners and rules

JUnit 4 marks tests with annotations, so a test class does not extend a base class, and a test method can have any name. @Before and @After run around each test, and @BeforeClass and @AfterClass run once for the class.25

Runners. A runner is the class that runs the tests of one class. "When a class is annotated with @RunWith or extends a class annotated with @RunWith , JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit."6 The default runner is BlockJUnit4ClassRunner.6 JUnit has runners for suites, for categories and for parameterized tests.6 A class has one @RunWith annotation, so it can use only one runner.

"Parameterized is a standard runner that implements parameterized tests."6 The class gives a static method with @Parameters that returns the rows, and the constructor takes one row. The name of @Parameters can use {index} and {0}, {1} for the values.13

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class GradeTest {
    static String grade(int score) {
        if (score >= 90) {
            return "A";
        }
        if (score >= 75) {
            return "B";
        }
        if (score >= 50) {
            return "C";
        }
        return "F";
    }

    @Parameters(name = "{0} gives {1}")
    public static Collection<Object[]> rows() {
        return Arrays.asList(new Object[][] {{95, "A"}, {75, "B"}, {74, "C"}, {10, "F"}});
    }

    private final int score;
    private final String expected;

    public GradeTest(int score, String expected) {
        this.score = score;
        this.expected = expected;
    }

    @Test
    public void gradeMatches() {
        assertEquals(expected, grade(score));
    }
}
Output
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
   └─ GradeTest ✔
      ├─ [95 gives A] ✔
      │  └─ gradeMatches[95 gives A] ✔
      ├─ [75 gives B] ✔
      │  └─ gradeMatches[75 gives B] ✔
      ├─ [74 gives C] ✔
      │  └─ gradeMatches[74 gives C] ✔
      └─ [10 gives F] ✔
         └─ gradeMatches[10 gives F] ✔

Test run finished after $TIME
[         8 containers found      ]
[         0 containers skipped    ]
[         8 containers started    ]
[         0 containers aborted    ]
[         8 containers successful ]
[         0 containers failed     ]
[         4 tests found           ]
[         0 tests skipped         ]
[         4 tests started         ]
[         0 tests aborted         ]
[         4 tests successful      ]
[         0 tests failed          ]

Rules. JUnit 4.7 added rules.14 "Rules allow very flexible addition or redefinition of the behavior of each test method in a test class."7 A TestRule "is an alteration in how a test method, or set of test methods, is run and reported."15 A field with @Rule "must be public, not static, and a subtype of TestRule (preferred) or MethodRule", and the rule applies to each test.16 A class can have more than one rule.16 @ClassRule is for static fields "that can affect the operation of a whole class".7 JUnit gives rules such as TemporaryFolder, ErrorCollector, TestName, Timeout and ExternalResource.7 ExternalResource is "a base class for Rules (like TemporaryFolder) that set up an external resource before a test".7 This rule sets the default locale before each test and puts the old one back after it:

import static org.junit.Assert.assertEquals;

import java.util.Locale;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class PriceFormatTest {
    @Rule
    public final ExternalResource germanLocale = new ExternalResource() {
        private Locale saved;

        @Override
        protected void before() {
            saved = Locale.getDefault();
            Locale.setDefault(Locale.GERMANY);
        }

        @Override
        protected void after() {
            Locale.setDefault(saved);
        }
    };

    @Test
    public void usesCommaForDecimals() {
        assertEquals("1,50", String.format("%.2f", 1.5));
    }

    @Test
    public void groupsThousandsWithDots() {
        assertEquals("1.234.567", String.format("%,d", 1234567));
    }
}
Output
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
└─ JUnit Vintage ✔
   └─ PriceFormatTest ✔
      ├─ groupsThousandsWithDots ✔
      └─ usesCommaForDecimals ✔

Test run finished after $TIME
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

Assumptions and matchers. JUnit 4.4 added assertThat with Hamcrest matchers, assumptions and theories.17 "Tests with failed assumptions are now marked as Ignored, rather than silently passing."17 JUnit 4.13 deprecated Assert.assertThat and recommends the assertThat of Hamcrest itself.11

Common tasks

Run JUnit 3 and JUnit 4 tests on the JUnit Platform. Put the Vintage engine and the JUnit 4 jar on the test class path. Then "JUnit 3 and JUnit 4 tests will automatically be picked up by the JUnit Platform launcher."8 The examples on this page run in this way. The guide also warns that the Vintage engine "is deprecated and should only be used temporarily while migrating tests".8

Migrate a JUnit 4 class to Jupiter. The migration guide lists the changes:8

JUnit 4 JUnit Jupiter
org.junit.Test org.junit.jupiter.api.Test
@Before, @After @BeforeEach, @AfterEach
@BeforeClass, @AfterClass @BeforeAll, @AfterAll
@Ignore @Disabled
@Category @Tag
@RunWith @ExtendWith
@RunWith(Parameterized.class) @ParameterizedClass or @ParameterizedTest
@Rule, @ClassRule @ExtendWith, @RegisterExtension
@Test(expected = ...), ExpectedException assertThrows
message as the first argument message as the last argument

The two versions use the same simple names in different packages. A class that takes some annotations from org.junit and some from org.junit.jupiter.api compiles, but each engine sees only its own annotations. JUnit 5 shows such a test that fails. Change the imports of one class at a time, and run the tests after each change.

Expect an exception. In JUnit 4.13 or later, use assertThrows. It returns the exception, so the test can check the message too.11 The ExpectedException rule is older, and JUnit 4.13 deprecated ExpectedException.none().11

Configuration

JUnit 4 has little configuration of its own. The build tool picks the test classes, and annotations configure each class. On the JUnit Platform, the Vintage engine reads configuration parameters. For example, junit.vintage.execution.parallel.enabled=true, together with junit.vintage.execution.parallel.classes=true or junit.vintage.execution.parallel.methods=true, runs JUnit 4 classes or methods in parallel.8

Alternatives

JUnit 5 and JUnit 6 are the current generations. New tests should use Jupiter. See JUnit 5.

TestNG started as a reaction to limits of JUnit. Its author writes: "I started TestNG out of frustration for some JUnit deficiencies".18 It has groups, dependencies between test methods and data providers. See TestNG.

History and versions

Martin Fowler tells the start: "JUnit was born on a flight from Zurich to the 1997 OOPSLA in Atlanta. Kent was flying with Erich Gamma".12 Beck had built small unit test frameworks in Smalltalk before.12 Fowler writes that "it's fair to give JUnit the credit for spreading the idea more."12 Ports to other languages followed, and the family took the name xUnit.12

JUnit 4 is now old. Its site says: "JUnit 4 is in maintenance mode."1 It adds: "At this point, only critical bugs and security issues will be fixed."1 JUnit 5.0.0 came in September 2017, and JUnit 6.0.0 in September 2025, with "Single version number for Platform, Jupiter, and Vintage".1920 In 6.1.3, "JUnit 6.1.3 = JUnit Platform + JUnit Jupiter + JUnit Vintage".21

The dates of JUnit 3 and JUnit 4 below are the dates of the version directories on Maven Central. The directories of 3.7, 3.8 and 3.8.1 have the same date and time, so their dates are those of an upload, not of the releases.9 The dates of JUnit 5 and JUnit 6 are those of the releases on GitHub.19

Version Date Notes
3.8.1 2005-09-20 The TestCase model: a base class, setUp and tearDown, and methods that start with test934
4.0 2006-02-18 The first JUnit 4 release on Maven Central9
4.4 2007-08-21 assertThat with Hamcrest matchers, assumptions and theories917
4.7 2009-08-12 Rules914
4.13 2020-01-01 assertThrows; Assert.assertThat and ExpectedException.none() deprecated911
4.13.2 2021-02-13 The last release of JUnit 49
5.0.0 2017-09-10 The JUnit Platform, Jupiter and Vintage; see JUnit 519
6.0.0 2025-09-30 One version number for all parts; Java 17 or later1920
6.1.3 2026-08-07 The current release at the date of this page19

References

  1. JUnit 4, About, the whole page
  2. JUnit FAQ, Overview, What is JUnit?; Writing Tests
  3. JUnit 4.13.2 source, junit.framework.TestCase, the class comment
  4. JUnit 4.13.2 source, junit.framework.TestSuite, the comment of the constructor TestSuite(Class)
  5. JUnit Cookbook, Simple Test Case; Fixture; Running Tests; Expected Exceptions
  6. JUnit 4 wiki, Test runners, @RunWith annotation; Specialized Runners
  7. JUnit 4 wiki, Rules, introduction; ExternalResource Rules
  8. JUnit User Guide 6.1.3, Migrating from JUnit 4, introduction; Running JUnit 4 Tests on the JUnit Platform; Migration Tips
  9. Maven Central, the directory junit/junit, the dates of the version directories
  10. JUnit User Guide 6.1.3, Build Support, Gradle, Configuring Test Engines
  11. JUnit 4.13 release notes, Add assertThrows; Deprecate Assert#assertThat; Deprecate ExpectedException.none()
  12. Martin Fowler, Xunit, bliki, 17 January 2006, the whole page
  13. JUnit 4 wiki, Parameterized tests, Identify Individual test cases
  14. JUnit 4.7 release notes, Rules
  15. JUnit 4.13.2 API, Interface TestRule, the class description
  16. JUnit 4.13.2 API, Annotation Type Rule, the description
  17. JUnit 4.4 release notes, assertThat; Assumptions; Theories
  18. TestNG Documentation, 1. Welcome to TestNG
  19. junit-team/junit-framework, Releases on GitHub, the releases r5.0.0, r6.0.0 and r6.1.3
  20. JUnit User Guide 6.1.3, Release Notes, 6.0.0
  21. JUnit User Guide 6.1.3, Overview, What is JUnit?

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B6HKSD/text.yaml