我想在我的 Java 测试框架中的单独线程中监视外部日志文件: 如果在其中一个受监视的日志文件中找到指定的模式,我的测试(在主线程中运行)应该立即失败。
我试图中断运行我的测试的线程,但是我必须在每个测试步骤之后检查 Thread.isInterrupted()
有没有正确的方法来做到这一点?
最佳答案
基本上,您不能以您想要的方式远程使测试失败。你关于中断线程的想法几乎是正确的事情,除了我会避免中断,而是将一个事件发布到,比如说,a LinkedBlockingQueue
which you poll at the end of the test to see if it is empty or not。 .
如果你想避免在每个测试方法中都这样做,你可以在用 @AfterMethod
注释的方法中添加检查。 .
像这样:
public class YourTest {
private LinkedBlockingQueue<String> errors;
@BeforeMethod
public void setUp() {
errors = new LinkedBlockingQueue<>();
}
private void checkLogsForErrors(){
// This is the method run in a separate thread.
for (String line: iterateOverLogEntries()) {
if (isError(line)) errors.add(line);
}
}
@AfterMethod
public void tearDown() {
try {
String error = errors.poll(100, TimeUnit.MILLISECONDS);
fail("Found error: " + error);
} catch (InterruptedException e){
// No errors, great!
}
}
}
编辑:哦,对了,马上。为什么不在单独的线程中运行测试代码本身,让原始线程等待来自日志观察器的错误信号或来自测试的成功信号?
关于java - 如何立即从另一个线程使 TestNG 测试失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20570182/