我通过实现org.junit.runner.Runner
创建了自己的JUnit-Runner,以便我可以使用@RunWith
- Annotation运行我的UnitTests。
看起来有点像这样:
public class MyRunner extends Runner {
private Context myContext;
myContext.init();
private final BlockJUnit4ClassRunner runner;
public MyRunner(final Class<?> clazz) throws InitializationError {
myContext = new Context();
runner = new BlockJUnit4ClassRunner(clazz);
}
@Override
public void run(final RunNotifier notifier) {
runner.run(notifier);
}
@Override
public Description getDescription() {
return runner.getDescription();
}
public void filter(final Filter filter) throws NoTestsRemainException {
runner.filter(filter);
}
}
要清理资源,我必须通过调用MyContext
关闭MyContext.close()
。我应该在哪里调用它,以便在测试运行后清理我的资源?
答案 0 :(得分:1)
我不确定你要做什么,但是你已经看过 JUnit's Rule
s 了吗?
public class MyContextRule extends ExternalResource {
private final Context myContext;
public MyContextRule() {
myContext = new Context();
}
@Override
protected void before() throws Throwable {
myContext.init();
}
@Override
protected void after() {
myContext.close();
}
}
用法:
public class MyTest {
@ClassRule
public static MyContextRule contextRule = new MyContextRule();
//...
}
JUnit Rule
优于Runner
的优点是你可以有多个,而你只能有一个跑步者。
因此,您的自定义Rule
可以与任何可能由您将来可能遇到的随机测试框架引入的跑步者一起使用...
答案 1 :(得分:-1)
我应该在哪里调用它,以便我的资源清理完毕 测试已经开始了?
更新了我的回答,您可以使用org.junit.runner.notification.RunListener
,如下所示:
(1)创建自己的RunListener类:
public class MyRunnerListener extends RunListener {
private Context context;
public MyRunnerListener(Context context) {
this.context = context;
}
void testRunFinished(Result result) {
context.close();
}
}
(2)在MyRunner中使用MyRunnerListener:
public class MyRunner extends Runner {
private Context myContext;
MyRunnerListener runnerListener;
private final BlockJUnit4ClassRunner runner;
public MyRunner(final Class<?> clazz) throws InitializationError {
myContext = new Context();
myContext.init();
runnerListener = new MyRunnerListener(myContext);
runner = new BlockJUnit4ClassRunner(clazz);
}
@Override
public void run(final RunNotifier notifier) {
notifier.addListener(runnerListener);
runner.run(notifier);
}
@Override
public Description getDescription() {
return runner.getDescription();
}
public void filter(final Filter filter) throws NoTestsRemainException {
runner.filter(filter);
}
}
PS:如果您不想使用Runner
,那么您可以按照Markus(使用TestRule
,而不是TestRunner
)的回答。强>