我有两个测试函数,每个我都希望有不同的@Before方法。怎么做到这一点?
答案 0 :(得分:0)
虽然在同一个类下组织所有测试似乎很方便,但对于您的情况,我认为最好的选择是将测试分成不同的类,每个类都有相应的setUp
。
另一种选择(我更喜欢上一个选项)可以直接在您的测试方法中调用setUp
,如下所示:
public class FooTest {
public void setUpMethod1() {
// do setUp things
}
public void setUpMethod2() {
// do setUp things
}
@Test
public void testMethod1() {
setUpMethod1();
// Test
}
@Test
public void testMethod2() {
setUpMethod2();
// Test
}
}
仅作为好奇心(IMO不推荐您的情况),您可以使用自己的实现覆盖默认的junit RunListener
。方法testStarted
在每次测试之前执行,您可以访问class和methodName以便能够识别正在运行的测试。虚拟样本:
public class MyRunListener extends RunListener {
@Override
public void testStarted(Description description) throws Exception {
//...
Class testClass = description.getClass();
String methodName = description.getMethodName();
//...
}
}
希望它有所帮助。