In this post under Junit 5, I will show how to disable a test method or all test methods of a class.
Junit 5 added a new annotation named “Disabled” to disable a test method or all the test methods of a class.
When applied at a particular method, that particular method is disabled.
When applied at a class level, all the test methods in that class are disabled.
For our example, we will use the below class
Class to be tested
package package6;
public class NumberUtil {
public boolean isEven(int number) {
if(number % 2 == 0) {
return true;
} else {
return false;
}
}
}
In the above code, we created a utility class named “NumberUtil” and it has “isEven” method which determines whether a number is even or not.
Below is the test class which will test “NumberUtil” class “isEven” method.
Test Class
1 package package6;
2
3 import static org.junit.jupiter.api.Assertions.assertFalse;
4 import static org.junit.jupiter.api.Assertions.assertTrue;
5
6 import org.junit.jupiter.api.BeforeEach;
7 import org.junit.jupiter.api.Disabled;
8 import org.junit.jupiter.api.Test;
9
10 public class NumberUtilTest {
11 private NumberUtil numberUtil;
12
13 @BeforeEach
14 public void setUp() {
15 numberUtil = new NumberUtil();
16 }
17
18 @Test
19 public void testNumberIsEven() {
20 assertTrue(numberUtil.isEven(10));
21 }
22
23 @Test
24 @Disabled
25 public void testNumberIsOdd() {
26 assertFalse(numberUtil.isEven(11));
27 }
28 }
In the above test class, we have two test methods named “testNumberIsEven” and “testNumberIsOdd”.
The test “testNumberIsOdd” is disabled by adding “Disabled” annotation. Refer to line 24.
So the end result is “testNumberIsEven” is executed but “testNumberIsOdd” is skipped.
When the same annotation is applied at the class level as shown below
1 package package6;
2
3 import static org.junit.jupiter.api.Assertions.assertFalse;
4 import static org.junit.jupiter.api.Assertions.assertTrue;
5
6 import org.junit.jupiter.api.BeforeEach;
7 import org.junit.jupiter.api.Disabled;
8 import org.junit.jupiter.api.Test;
9
10 @Disabled
11 public class NumberUtilTest {
12 .
13 .
14 .
15 }
So in this case both methods “testNumberIsEven” and “testNumberIsOdd” are disabled.
In this way we can disable all methods in a class or a particular method.