JUnit Disable Tests Examples


In this article, we will discuss the usage of JUnit @Disabled annotation with an example.

We use @Ignore annotation is used to disable or ignore the tests in JUnit 4. JUnit 5 provides a @Disabled annotation to disable test class or test methods.

JUnit Disabling Tests Example

JUnit @Disabled annotation is the easiest way to disable a test. It can be applied to a test method as well as to the Class itself. If @Disabled annotation is applied to the class, then all the tests present in the class gets disabled. We can also specify a reason message for documentation purposes. 

Disable Test Class

Use @Disabled annotation to disable the entire test class. If @Disabled annotation is applied to the class, then all the tests present in the class get disabled. 
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

@Disabled
class DisabledClassDemo {
    
    @Test
    void test1() {
     System.out.println("test 1");
    }
    
    @Test
    void test2() {
     System.out.println("test 2");
    }
    
    @Test
    void test3() {
     System.out.println("test 2");
    }
}

Disable Test Method

Use @Disabled annotation to disable the JUnit test method.
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

class DisabledTestsDemo {

    @Disabled
    @Test
    void testWillBeSkipped() {
    }

    @Test
    void testWillBeExecuted() {
    }
}

Conclusion

In this post, we used @Disabled annotation to disable or ignore the tests in JUnit 5. We can disable either class or test method.

Comments