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.
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
| Scenario | Use It? |
|---|---|
| Feature not implemented yet | Yes |
| Bug in the test | Yes |
| External service or dependency down | Yes |
| Permanent skipping of tests | No (Better to remove or handle properly) |
No comments:
Post a Comment