Skip a test method using @Disabled annotation
Preconditions (2)
✅ Expected Result: The test method annotated with @Disabled is skipped and not executed. Other test methods run and pass or fail as usual.
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class DisabledTestExample { @Test void activeTest() { assertTrue(5 > 2, "Active test should run and pass"); } @Disabled("Skipping this test temporarily due to bug #123") @Test void skippedTest() { // This test will be skipped assertTrue(false, "This test should be skipped and not fail"); } }
The code defines two test methods inside a test class.
The activeTest method is a normal test and will run when the tests are executed.
The skippedTest method is annotated with @Disabled and a reason string. This tells JUnit to skip this test during execution.
Assertions inside activeTest verify normal behavior. The assertion inside skippedTest would fail if run, but since the test is disabled, it is not executed, so no failure occurs.
This setup helps temporarily skip tests without deleting or commenting them out.
Now add a third test method that is conditionally disabled only on Windows OS
@Disabled annotation in JUnit?@Disabled@Disabled annotation tells JUnit to skip running the test method or class.@Disabled with an optional string reason in parentheses and quotes.@Disabled("Waiting for bug fix")
public class CalculatorTests {
@Test
public void testAdd() { /* test code */ }
@Test
public void testSubtract() { /* test code */ }
}
What will happen when this test class runs?@Disabled is on a class, all tests inside are skipped.testAdd and testSubtract will be skipped, and the reason "Waiting for bug fix" will be shown in reports.@Disabled("Feature incomplete")
public void testFeature() {
assertEquals(5, 2 + 3);
}
But when you run tests, this method still runs. What is the likely problem?@Test annotation to recognize a method as a test.@Disabled but lacks @Test, so JUnit ignores it as a test and does not skip it.@Disabled("Reason") on test methods skips them and shows the reason in reports.@Test hides tests but does not show skip reasons. Disabling whole class skips all tests without selective reasons.Pass the test and this pattern moves unknown