Ignore Test in JUnit

  

In JUnit, sometimes you may want to ignore a test method or class temporarily—perhaps because it's not working yet or depends on something not yet implemented. JUnit provides the @Disabled annotation (in JUnit 5) or @Ignore annotation (in JUnit 4) to skip test execution.


Ignoring Tests in JUnit 5

JUnit 5 uses:

import org.junit.jupiter.api.Disabled;

Usage:

  • Annotate the test method or class with @Disabled.

  • You can also provide a reason for disabling.



Example:


import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;

public class CalculatorTest {

    @Test
    public void testAddition() {
        int result = 2 + 3;
        assert(result == 5);
    }

    @Disabled("Test is under development")
    @Test
    public void testSubtraction() {
        int result = 5 - 2;
        assert(result == 4); // Intentionally incorrect
    }
}


Output:

testAddition() will run.

testSubtraction() will be skipped with the message Test is under development.




Ignoring Tests in JUnit 4

JUnit 4 uses:


import org.junit.Ignore;




Example:


import org.junit.Test;
import org.junit.Ignore;

public class CalculatorTest {

    @Test
    public void testMultiplication() {
        int result = 3 * 4;
        assert(result == 12);
    }

    @Ignore("Pending bug fix")
    @Test
    public void testDivision() {
        int result = 10 / 2;
        assert(result == 6); // Incorrect assertion
    }
}


Output:

  • testMultiplication() runs.

  • testDivision() is ignored.




Ignoring an Entire Test Class

You can ignore all tests in a class:

JUnit 5:


@Disabled("Integration not ready")
public class IntegrationTest {
    @Test
    void testServiceCall() {
        // code
    }
}




JUnit 4:


@Ignore("Work in progress")
public class IntegrationTest {
    @Test
    public void testSomething() {
        // code
    }
}




When to Use @Disabled / @Ignore


ScenarioUse It?
Feature not implemented yetYes
Bug in the testYes
External service or dependency downYes
Permanent skipping of testsNo (Better to remove or handle properly)



JUnit Test Suite

  

To execute a JUnit 5 test suite, you need to use the @Suite and related annotations provided by JUnit Platform. These annotations allow grouping and running multiple test classes together as a single test suite.


Key Annotations Used in JUnit 5 Suite


AnnotationDescription
@SuiteMarks the class as a test suite.
@SelectClassesSpecifies the test classes to include in the suite.
@SelectPackages(Optional) Runs all tests in the given package.
@IncludeTags / @ExcludeTags(Optional) Filters test methods by tags.



The test suite must not have any test methods of its own. It just aggregates other test classes.

Maven/Gradle Dependency

JUnit 5 uses the junit-platform-suite module:


<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-suite</artifactId>
    <version>1.10.0</version>
    <scope>test</scope>
</dependency>



Also include JUnit Jupiter:


<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.10.0</version>
    <scope>test</scope>
</dependency>




Example: How to Execute JUnit 5 Test Suite

Step 1: Create Sample Test Classes


// File: CalculatorTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    @Test
    void testAddition() {
        assertEquals(4, 2 + 2);
    }

    @Test
    void testSubtraction() {
        assertEquals(0, 2 - 2);
    }
}



// File: StringUtilsTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class StringUtilsTest {

    @Test
    void testToUpperCase() {
        assertEquals("HELLO", "hello".toUpperCase());
    }

    @Test
    void testLength() {
        assertEquals(5, "hello".length());
    }
}




Step 2: Create Test Suite Class


// File: AllTestsSuite.java
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({
    CalculatorTest.class,
    StringUtilsTest.class
})
public class AllTestsSuite {
    // No code needed here
}




How to Run the Suite

Option 1: From IDE (like Eclipse/IntelliJ)

  • Right-click on AllTestsSuite.java → Run As → JUnit Test.

Option 2: Using Maven

Run the tests with:

mvn test


JUnit Test Runner

  

What is a JUnit Test Runner?

JUnit Test Runner is the component in JUnit responsible for executing test cases. It defines how tests are discovered, initialized, and run. JUnit provides built-in runners, but you can also create custom runners.


Common JUnit Test Runners


Test RunnerDescription
BlockJUnit4ClassRunnerDefault runner for JUnit 4. Runs tests in a class using annotations like @Test, @Before, @After.
ParameterizedAllows running the same test with different inputs.
SuiteRuns multiple test classes together. Useful for integration testing.
SpringJUnit4ClassRunnerUsed in Spring testing to load the Spring context.



How to Use a Test Runner in JUnit

You attach a runner using the @RunWith annotation on top of your test class:


@RunWith(BlockJUnit4ClassRunner.class)
public class MyTestClass {
    // Your test methods
}


However, if you're using basic JUnit 4 tests, you don’t need to specify @RunWith, because BlockJUnit4ClassRunner is the default.


Example 1: Using Default Runner (JUnit 4)


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

public class CalculatorTest {

    @Test
    public void testAddition() {
        int result = 2 + 3;
        assertEquals(5, result);
    }

    @Test
    public void testSubtraction() {
        int result = 5 - 2;
        assertEquals(3, result);
    }
}




Here, JUnit uses the default BlockJUnit4ClassRunner implicitly.

Example 2: Using @RunWith(Suite.class) to Run Multiple Classes


import org.junit.runner.RunWith;
import org.junit.runners.Suite;

// List the test classes
@RunWith(Suite.class)
@Suite.SuiteClasses({
    CalculatorTest.class,
    StringUtilsTest.class
})
public class AllTests {
    // No code needed here
}



This AllTests class acts as a test suite runner.

Example 3: Using @RunWith(Parameterized.class) for Data-Driven Testing


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

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class MultiplyTest {

    private int a, b, expected;

    public MultiplyTest(int a, int b, int expected) {
        this.a = a;
        this.b = b;
        this.expected = expected;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> testData() {
        return Arrays.asList(new Object[][] {
            {2, 3, 6},
            {4, 5, 20},
            {3, 3, 9}
        });
    }

    @Test
    public void testMultiplication() {
        assertEquals(expected, a * b);
    }
}


This uses Parameterized runner to run the test method multiple times with different input sets.

What is a Test Runner in JUnit 5?

In JUnit 5, the concept of a Test Runner is abstracted away — it's handled internally by the JUnit Platform.

You don't explicitly use @RunWith anymore. Instead, you rely on annotations like @Test@BeforeEach@AfterEach, and engines like:

  • junit-jupiter-engine – runs JUnit 5 tests

  • junit-vintage-engine – runs legacy JUnit 3 & 4 tests


JUnit 5 integrates well with tools like Maven, Gradle, Eclipse, IntelliJ, and CI tools, and the runner is embedded in these integrations.


JUnit 5 Parameterized Test Example

In JUnit 5, you use the @ParameterizedTest annotation with sources like @ValueSource@CsvSource, etc.


import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class NumberTest {

    @ParameterizedTest
    @ValueSource(ints = {2, 4, 6, 8})
    void testEvenNumbers(int number) {
        assertTrue(number % 2 == 0);
    }
}

This is similar to @RunWith(Parameterized.class) in JUnit 4.

First JUnit Test

 

Here's a step-by-step guide to writing your first JUnit test in Eclipse, using JUnit 5 (also known as JUnit Jupiter).


Step 1: Set Up Eclipse Project

  • Open Eclipse.
  • Go to File → New → Java Project.
  • Name the project, example: JUnitDemo.
  • Click Finish.


Step 2: Add JUnit 5 Library

  • Right-click the project → Build Path → Add Libraries.
  • Select JUnit → Click Next.
  • Choose JUnit 5 → Click Finish.


If JUnit 5 is not available, you may need to download JUnit 5 from Maven/Gradle or manually add its .jar files.



Step 3: Create a Class to Test

Create a Java class that has some logic you want to test.


// File: Calculator.java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}



Step 4: Create a JUnit Test Class

  • Right-click on the src folder → New → JUnit Test Case.
  • Name it CalculatorTest.
  • Select JUnit 5 as the version.
  • Click Finish.



Step 5: Write Your First Test


// File: CalculatorTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    @Test
    public void testAddition() {
        Calculator calc = new Calculator();
        int result = calc.add(10, 5);
        assertEquals(15, result, "10 + 5 should equal 15");
    }
}


Step 6: Run the Test

  • Right-click on CalculatorTest.java.
  • Select Run As → JUnit Test.


JUnit 5 Key Annotations


AnnotationDescription
@TestMarks a method as a test method
@BeforeEachRuns before each test method
@AfterEachRuns after each test method
@BeforeAllRuns once before all test methods (static)
@AfterAllRuns once after all test methods (static)
@DisabledDisables a test temporarily


JUnit Annotations

  

JUnit annotations are metadata tags used in Java unit testing with the JUnit framework. These annotations help control test execution, such as setup, teardown, test methods, and expected outcomes.


Common JUnit Annotations (JUnit 5)


AnnotationDescription
@TestMarks a method as a test method.
@BeforeEachRuns before each test method. Used for setup.
@AfterEachRuns after each test method. Used for cleanup.
@BeforeAllRuns once before all test methods. Must be static.
@AfterAllRuns once after all test methods. Must be static.
@DisabledDisables a test method or class.
@DisplayNameCustom name for test class or method when displayed in test results.
@NestedDeclares nested test classes for better grouping.
@TagAdds a tag for filtering or grouping tests (e.g., fast, slow, integration).




Example Code Using JUnit Annotations


import org.junit.jupiter.api.*;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CalculatorTest {

    Calculator calculator;

    @BeforeAll
    void setupAll() {
        System.out.println("Initializing test class...");
    }

    @BeforeEach
    void setup() {
        calculator = new Calculator();
        System.out.println("Setting up before a test...");
    }

    @Test
    @DisplayName("Addition Test")
    void testAddition() {
        Assertions.assertEquals(5, calculator.add(2, 3));
    }

    @Test
    @DisplayName("Subtraction Test")
    void testSubtraction() {
        Assertions.assertEquals(1, calculator.subtract(4, 3));
    }

    @Test
    @Disabled("Feature not yet implemented")
    void testMultiplication() {
        Assertions.assertEquals(6, calculator.multiply(2, 3));
    }

    @AfterEach
    void tearDown() {
        System.out.println("Cleaning up after a test...");
    }

    @AfterAll
    void tearDownAll() {
        System.out.println("All tests completed.");
    }
}

// Simple Calculator class
class Calculator {
    int add(int a, int b) { return a + b; }
    int subtract(int a, int b) { return a - b; }
    int multiply(int a, int b) { return a * b; }
}



Important Points:

  • @BeforeEach and @AfterEach are useful for per-test setup and teardown.

  • @BeforeAll and @AfterAll are run once before and after all tests.

  • @Disabled is used to skip tests.

  • Assertions is used to check expected vs actual outcomes.

Introduction of JUnit

  

JUnit is a unit testing framework for the Java programming language. It plays a crucial role in test-driven development (TDD) and is used to write and run repeatable tests. JUnit belongs to the family of XUnit frameworks, and it is one of the most popular testing libraries in Java.


Key Features of JUnit


FeatureDescription
AnnotationsUses annotations like @Test@BeforeEach@AfterEach@BeforeAll@AfterAll, etc.
AssertionsProvides assertion methods like assertEquals()assertTrue(), etc.
Test RunnerJUnit provides test runners to run test classes individually or as part of a suite.
IntegrationEasily integrates with build tools like Maven/Gradle and IDEs like Eclipse, IntelliJ.



Common JUnit Annotations


AnnotationDescription
@TestMarks a method as a test method
@BeforeEachRuns before each test method
@AfterEachRuns after each test method
@BeforeAllRuns once before all test methods (must be static)
@AfterAllRuns once after all test methods (must be static)
@DisabledSkips a test method or class



Simple Example of JUnit (JUnit 5)

Java Class to Test (Calculator.java)


public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}



Test Class (CalculatorTest.java)


import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.*;

public class CalculatorTest {

    Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
        System.out.println("Before Each Test");
    }

    @AfterEach
    void tearDown() {
        System.out.println("After Each Test");
    }

    @Test
    void testAddition() {
        assertEquals(5, calculator.add(2, 3), "2 + 3 should equal 5");
    }

    @Test
    void testSubtraction() {
        assertEquals(1, calculator.subtract(3, 2), "3 - 2 should equal 1");
    }
}


How to Run JUnit Tests

You can run JUnit tests in several ways:

  • From IDE like Eclipse/IntelliJ (Right-click → Run As → JUnit Test)

  • Using build tools like Maven/Gradle

  • Command line (using javac and java with JUnit jars)



Maven Dependency for JUnit 5

If you're using Maven:


<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.10.0</version>
    <scope>test</scope>
</dependency>




Important Points:

  • JUnit helps automate and structure your unit tests.
  • It promotes cleaner code and faster debugging.
  • Easily integrates with CI/CD tools, Maven, and IDEs.
  • Essential for TDD and Agile methodologies.