How to Use @Disabled Annotation in JUnit Tests
In JUnit, use the
@Disabled annotation to skip a test method or class temporarily. Place @Disabled above the test method or class to prevent it from running during test execution.Syntax
The @Disabled annotation can be applied to a test method or an entire test class to disable it. Optionally, you can provide a reason as a string to explain why the test is disabled.
@Disabled: disables the test without a reason.@Disabled("reason"): disables the test with a reason message.
java
@Disabled void testMethod() { // test code } @Disabled("Waiting for bug fix") void anotherTestMethod() { // test code }
Example
This example shows a test class with one enabled test and one disabled test. The disabled test will be skipped during execution, and the test report will indicate it was disabled.
java
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @Test void additionWorks() { assertEquals(5, 2 + 3); } @Test @Disabled("Feature not implemented yet") void subtractionWorks() { assertEquals(1, 3 - 2); } }
Output
Test run finished after 50 ms
[ 2 containers found ]
[ 0 containers skipped ]
[ 2 containers started ]
[ 0 containers aborted ]
[ 1 containers successful ]
[ 0 containers failed ]
[ 2 tests found ]
[ 1 tests skipped ]
[ 0 tests aborted ]
[ 1 tests successful ]
Tests skipped: 1 - Feature not implemented yet
Common Pitfalls
Common mistakes when using @Disabled include:
- Forgetting to remove
@Disabledafter fixing the issue, causing tests to remain skipped unintentionally. - Using
@Disabledwithout a reason, which makes it harder to track why a test is disabled. - Applying
@Disabledon a test class without realizing all tests inside will be skipped.
java
/* Wrong: Disabled without reason */ @Disabled @Test void testWithoutReason() { // test code } /* Right: Disabled with reason */ @Disabled("Waiting for bug fix") @Test void testWithReason() { // test code }
Quick Reference
Summary tips for using @Disabled:
- Use
@Disabledto skip tests temporarily. - Always provide a reason to document why the test is disabled.
- Remember to re-enable tests after the issue is resolved.
- Can be applied to methods or entire classes.
Key Takeaways
Use @Disabled to skip tests temporarily in JUnit.
Always add a reason in @Disabled to explain why the test is disabled.
@Disabled can be applied to both test methods and classes.
Remember to remove @Disabled once the test should run again.
Disabled tests appear in reports as skipped, not failed.