JUnit 4 Documentation

repository·main·Indexed 27 days ago

https://github.com/junit-team/junit4

A unit testing framework based on the xUnit architecture designed for writing repeatable tests. This documentation covers core features, rules such as TemporaryFolder and Timeout, the Parameterized runner, and release notes for versions 4.10 through 4.12. Note that JUnit 4 is in maintenance mode; for active development, use the junit-framework repository.

Tokens
12.5K
Snippets
36
Records
85
Agent score
94%

What's inside JUnit 4

  1. Overview of JUnit 4

    main

    JUnit 4 is a simple framework for writing repeatable tests, based on the xUnit architecture for unit testing frameworks.

    Note: JUnit 4 is in maintenance mode. Only critical bugs and security issues are addressed. For active development and new features, use the junit-framework repository instead.

  2. Categorize tests using @Category

    main

    In JUnit 4.5, you can annotate test classes or individual test methods with @Category to group them. This allows you to run specific subsets of tests (e.g., only UI tests or only integration tests).

    To run tests belonging to a specific category, you must create a custom Request using JUnitCore.

    public static class SomeUITests {
        @Category(UserAvailable.class)
        @Test
        public void askUserToPressAKey() { }
        
        @Test
        public void simulatePressingKey() { }
    }
        
    @Category(InternetConnected.class)
    public static class InternetTests {
        @Test
        public void pingServer() { }
    }
    
    // To run only UserAvailable tests:
    new JUnitCore().run(Request.aClass(SomeUITests.class).inCategories(UserAvailable.class));
  3. Build JUnit 4 from source using Maven

    main

    To build the JUnit project from the source code, you must have Maven installed. After cloning the repository and navigating to the project root, you can clean the previous build, build the project, and install the new artifacts into your local repository (~/.m2/repository) using the clean install goal.

    Ensure you set the M2_HOME and PATH environment variables if you plan to build frequently via the command line.

  4. Configure Timeout Rule to look for stuck threads

    main

    In JUnit 4.13.2, the Timeout rule only creates a new ThreadGroup if lookForStuckThread(true) is explicitly called via the builder. If your tests rely on the behavior introduced in JUnit 4.12 where a new ThreadGroup was always created (which may be necessary for tests interacting with java.beans.ThreadGroupContext), you must use the Timeout.Builder to enable this feature.

    To restore the JUnit 4.12 behavior in version 4.13.2, use Timeout.Builder.lookForStuckThread(true).

  5. Write a simple test case

    main

    To write a basic test in JUnit 4:

    1. Annotate a method with @org.junit.Test.
    2. Use org.junit.Assert.* (specifically assertTrue()) to verify results by passing a boolean expression that evaluates to true if the test succeeds.
    @Test
    public void simpleAdd() {
        Money m12CHF= new Money(12, "CHF");
        Money m14CHF= new Money(14, "CHF");
        Money expected= new Money(26, "CHF");
        Money result= m12CHF.add(m14CHF);
        assertTrue(expected.equals(result));
    }
  6. Use the correct Maven artifact for JUnit

    main

    When using Maven, you should use the junit:junit artifact.

    Previously, junit:junit-dep was used to avoid including Hamcrest classes in the artifact, but junit:junit is now the standard. If you still reference junit:junit-dep, Maven will automatically relocate you to junit:junit and issue a warning.

  7. Enable strict resource deletion in TemporaryFolder

    main

    By default, the TemporaryFolder rule does not fail a test if some temporary resources cannot be deleted. You can enable strict verification by using the TemporaryFolder.builder() method with the assureDeletion() parameter. If enabled, an AssertionError will be thrown if resource deletion fails.

    @Rule public TemporaryFolder folder = TemporaryFolder.builder().assureDeletion().build();
  8. Access JUnit 4 documentation and guides

    main

    For detailed information on using JUnit 4, refer to the following resources:

    • Wiki: General project information.
    • Download and Install guide: Instructions for obtaining and setting up the framework.
    • Getting Started: Initial steps to begin writing tests.
  9. Import and build JUnit 4 Maven project in Eclipse

    main
    1. In Eclipse, go to File -> Import....
    2. Select Maven -> Existing Maven Projects and click Next.
    3. Specify the project root directory and proceed with installing the Maven support plugin if prompted.
    4. To build, right-click pom.xml in the Package Explorer.
    5. Select Run -> Run As -> 2 Maven build....
    6. In the Edit Configuration popup, enter clean install in the Goals section and click Run.
  10. Run tests via JUnitCore

    main

    You can run tests and view results on the console using org.junit.runner.JUnitCore.

    From a Java program:

    org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);

    From the command line (ensure both your test class and JUnit are on the classpath):

    java org.junit.runner.JUnitCore TestClass1.class [...other test classes...]

    Compatibility with older TestRunners: To make JUnit 4 test classes accessible to TestRunners designed for earlier versions, declare a static suite() method that returns a junit.framework.Test using a JUnit4TestAdapter.

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(Example.class);
    }
  11. Configure Categories for test execution

    main

    The Categories runner allows you to include or exclude tests based on @Category annotations. Categories can be classes or interfaces.

    • Include Categories: Use @Categories.IncludeCategory(category) to run tests marked with that category or its subtypes.
    • Exclude Categories: Use @Categories.ExcludeCategory(category) to skip tests marked with that category.
    • Multiple Categories (OR logic): By default, providing multiple categories to @IncludeCategory acts as an OR condition (runs tests matching any of the categories).
    • Multiple Categories (AND logic): To run only tests that match all provided categories, set matchAny = false in the @IncludeCategory annotation.
    • Inheritance: Since @Category is @Inherited, categories applied to a superclass will be inherited by subclasses.
    public static interface FastTests { /* category marker */ }
    public static interface SlowTests { /* category marker */ }
    public static interface SmokeTests { /* category marker */ }
    
    public static class A {
        @Category(SlowTests.class)
        @Test
        public void b() {}
    
        @Category({FastTests.class, SmokeTests.class})
        @Test
        public void c() {}
    }
    
    @RunWith(Categories.class)
    @Categories.IncludeCategory(SlowTests.class)
    @Suite.SuiteClasses({A.class})
    public static class SlowTestSuite {
        // Will run A.b
    }
    
    @RunWith(Categories.class)
    @Categories.IncludeCategory(value = {FastTests.class, SmokeTests.class}, matchAny = false)
    @Suite.SuiteClasses({A.class})
    public static class FastAndSmokeTestSuite {
        // Will run only A.c (matches both)
    }