In this post we will learn how to disable or ignore a test using @Test(enabled=false)
. Occasionally, we want to disable some tests because of some reasons(like a particular api being tested in those tests is changing but we don’t want to stop the complete CI build which apart from this API should be working fine). In those situations, we can simply ignore/disable those tests by setting enabled attribute of @Test annotation to false. Let’s begin.
Let’s take a simple Calculator class to demonstrate this feature.
package com.websystique.testng; public class Calculator { public double add(double a, double b){ return a+b; } public double subtract(double a, double b){ return a-b; } }
Let’s write a trivial test class with two test methods add & subtract. Let’s assume that subtract api is broken and we don’t want to execute subtract test method for the moment.
package com.websystique.testng; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestNGEnabledExample { Calculator calculator; @BeforeClass public void setup() { System.out.println("setup()"); calculator = new Calculator(); } @AfterClass public void tearDown() { System.out.println("tearDown()"); calculator = null; } @BeforeMethod public void beforeMethod() { System.out.println("beforeMethod()"); } @AfterMethod public void afterMethod() { System.out.println("afterMethod()"); } @Test public void testAdd() { System.out.println("testAdd()"); Assert.assertEquals(calculator.add(3, 4), 7.0); } @Test(enabled = false) public void testSubtract() {//We are disabling this test. Look at enabled=false with @Test System.out.println("testSubtract()"); Assert.assertEquals(calculator.subtract(5, 2), 3.0); } }
We have also included the @BeforeClass & @BeforeMethod to see the overall effect.
Run above test class using TestNG Eclipse plugin or maven (mvn clean test). Following is the outcome:
setup() beforeMethod() testAdd() afterMethod() tearDown() PASSED: testAdd =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 ===============================================
You can see that we have disabled the subtract test method by using @Test(enabled=false). So that subtract Test method wasn’t executed.
Additional noticeable points are :
- @BeforeClass/@AfterClass was called as there is at least one @Test method in this class which got executed.
- @BeforeMethod/@AfterMethod was called only for the @Test method which got executed. For the @Test which was disabled, no @BeforeMethod/@AfterMethod was called.
That’s it.
References
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.