Junit's @BeforeClass
and @AfterClass
必须声明为静态。有一个很好的解决方法here https://stackoverflow.com/questions/32952884/junit-beforeclass-non-static-work-around-for-spring-boot-application/32956539#32956539 for @BeforeClass
。我的班级中有许多单元测试,只想初始化和清理一次。有关如何找到解决方法的任何帮助@AfterClass
?我想使用 Junit 而不引入额外的依赖项。谢谢!
如果您想要类似于提到的解决方法@BeforeClass
,您可以跟踪已经运行了多少测试,然后一旦运行了所有测试,最后执行您的结束清理代码。
public class MyTestClass {
// ...
private static int totalTests;
private int testsRan;
// ...
@BeforeClass
public static void beforeClass() {
totalTests = 0;
Method[] methods = MyTestClass.class.getMethods();
for (Method method : methods) {
if (method.getAnnotation(Test.class) != null) {
totalTests++;
}
}
}
// test cases...
@After
public void after() {
testsRan++;
if (testsRan == totalTests) {
// One time clean up code here...
}
}
}
这假设您使用的是 JUnit 4。如果您需要考虑从超类继承的方法,请参阅this https://stackoverflow.com/questions/28400408/what-is-the-new-way-of-getting-all-methods-of-a-class-including-inherited-defau因为这个解决方案没有继承方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)