我正在编写在其工作期间启动多个服务器的集成测试。在任何可能的情况下,我都需要确保在测试后关闭它们,包括使用IDE进行手动测试停止。有没有办法实现这个目标?
答案 0 :(得分:1)
您可以通过注册关机挂钩来覆盖几乎所有停止/停止方案:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Gracefully shutting down the application/test");
}
});
但是,如果有人发出kill -9
,那么即使shutdownHook也不会捕获,因为操作系统会处理此信号,导致/中止该过程,甚至不再向其发送控制。
答案 1 :(得分:1)
一个不错的选择是在自定义JUnit运行器中使用关闭钩子,例如:
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class MyRunner extends BlockJUnit4ClassRunner {
public MyRunner(Class<?> klass) throws InitializationError {
super(klass);
Runtime.getRuntime().addShutdownHook(new Thread("app-shutdown-hook") {
@Override
public void run() {
// Your code here
System.out.println("End of test");
}
});
}
}
然后,使用此跑步者来运行测试:
@RunWith(MyRunner.class)
public class MyTest {
@Test
public void test() {
System.out.println("My test");
}
}