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)



No comments:

Post a Comment