Chr*_*way 27 java junit assertions
我已经assert
在JUnit测试套件中没有失败的Java 语句中进行了几次,因为在JUnit的JVM实例中没有启用断言.要清楚,这些是实现中的"黑盒子"断言(检查不变量等),而不是JUnit测试本身定义的断言.当然,我想在测试套件中捕获任何这样的断言失败.
显而易见的解决方案是要非常小心使用-enableassertions
,每当我运行JUnit,但我更喜欢一个更强大的解决方案.一种替代方法是将以下测试添加到每个测试类:
@Test(expected=AssertionError.class)
public void testAssertionsEnabled() {
assert(false);
}
Run Code Online (Sandbox Code Playgroud)
有没有更自动的方法来实现这一目标?JUnit的系统范围配置选项?我可以在setUp()
方法中添加动态调用吗?
RAb*_*ham 21
在Eclipse中你可以去Windows
→交通Preferences
→交通Java
→交通JUnit
,其中有一个选项来增加-ea
每次创建一个新的启动配置.它还-ea
为调试配置添加了选项.
复选框旁边的全文是
在创建新的JUnit启动配置时,将"-ea"添加到VM参数
我建议三种可能(简单?)修复,在快速测试后对我有用(但你可能需要检查使用静态初始化程序块的副作用)
1.)将静态初始化程序块添加到依赖于启用断言的那些测试用例中
import ....
public class TestXX....
...
static {
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
}
...
@Test(expected=AssertionError.class)
...
...
Run Code Online (Sandbox Code Playgroud)
2.)创建一个基类,所有测试类都扩展,需要启用断言
public class AssertionBaseTest {
static {
//static block gets inherited too
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
}
}
Run Code Online (Sandbox Code Playgroud)
3.)创建一个运行所有测试的测试套件
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
//list of comma-separated classes
/*Foo.class,
Bar.class*/
})
public class AssertionTestSuite {
static {
//should run before the test classes are loaded
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
}
public static void main(String args[]) {
org.junit.runner.JUnitCore.main("AssertionTestSuite");
}
}
Run Code Online (Sandbox Code Playgroud)