JUnit 提供注解 org.junit.Ignore 用于暂时忽略某个测试方法或者说整个类。因为有时候由于测试环境受限,并不能保证每一个测试方法都能正确运行。
1,方法级别上使用@ignore来注释我们的测试方法,结果就是该方法在测试执行时会被跳过。测试结束后,还可以获取详细的统计信息,不仅包括了测试成功和测
试失败的次数,也包括了被忽略的测试数目。
例如下面的代码便表示由于没有了数据库链接,提示 JUnit 忽略测试方法 unsupportedDBCheck:
package test.junit4test; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class LinkinTest { @Ignore @Test public void test1() { Assert.assertTrue(true); } @Test public void test2() { Assert.assertTrue(true); } }
2,类级别上使用@ignore来修饰整个类。这个类中所有的测试都将被跳过。
package test.junit4test; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @Ignore public class LinkinTest { @Test public void test1() { Assert.assertTrue(true); } @Test public void test2() { Assert.assertTrue(true); } }
关于上面的忽略测试一定要小心。注解 org.junit.Ignore 只能用于暂时的忽略测试,如果需要永远忽略这些测试,一定要确认被测试代码不再需要这些测试方法,以免忽略必要的测试点。