JUnit @Disabled Example
May 03, 2021
On this page we will learn using JUnit @Disabled
annotation.
1. JUnit
@Disabled
annotation is introduced in JUnit 5. The @Disabled
annotation is JUnit Jupiter API.
2. The
@Disabled
annotation is used to disable test methods. A disabled test method will not execute in unit test run.
3. The
@Disabled
annotation can be used at method level as well as class level.
4. When
@Disabled
is used at class level, all the test methods are disabled and they are not executed.
5. When
@Disabled
annotation is used at method level, then that method will not execute in test run. For @Disabled
methods, their lifecycle callbacks such as @BeforeEach
method and @AfterEach
method will also not execute.
6. In a test class, if some test methods are annotated with
@Disabled
annotation then these test methods will not execute but other test methods will execute normally.
7. The
@Disabled
annotation optionally accepts a string data i.e. the description for disabling the test to execute.
@Disabled("Disabled until bug #123 is fixed.") @Test void additionTest() { ------ }
@Disabled
annotation helps in documenting and reporting for disabled tests.
@Disabled at Method Level
Here we will disable a test method using@Disabled
annotation. We just have to annotate the test method with @Disabled
. We can optionally pass the reason for disabling this method to this annotation.
MyAppTest1.java
public class MyAppTest1 { @BeforeEach void init(TestInfo testInfo) { System.out.println("Start..." + testInfo.getDisplayName()); } @Disabled("Disabled until bug #123 is fixed.") @Test void additionTest() { int sum = 50 + 60; assertEquals(110, sum); } @Test void multiplyTest() { int multi = 15 * 5; assertEquals(75, multi); } @AfterEach void tearDown(TestInfo testInfo) { System.out.println("Finished..." + testInfo.getDisplayName()); } }
Start...multiplyTest() Finished...multiplyTest()
additionTest()
will not execute. The @BeforeEach
and @AfterEach
methods for additionTest()
will also not execute.
The
multiplyTest
method will execute normally with @BeforeEach
and @AfterEach
methods.
@Disabled at Class Level
Here we will use@Disabled
annotation at class level. Once a class is annotated with @Disabled
annotation, all the test methods of that class are disabled.
MyAppTest2.java
@Disabled("Disabled until change in User functionality is completed.") public class MyAppTest2 { @BeforeEach void init(TestInfo testInfo) { System.out.println("Start..." + testInfo.getDisplayName()); } @Test void additionTest() { int sum = 60 + 40; assertEquals(100, sum); } @Test void multiplyTest() { int multi = 20 * 5; assertEquals(100, multi); } @AfterEach void tearDown(TestInfo testInfo) { System.out.println("Finished..." + testInfo.getDisplayName()); } }
Find the print screen of the output.
