首页 > 解决方案 > 在 Assert.fail() 之后 Java 程序不会终止

问题描述

我有一个 Java 程序,我试图在最后使用 Assert.fail() 使我的测试失败,但是在程序结束时,线程继续运行并且程序没有结束。

@Test()
void function(){
try {
        post_call =  service.submit(new Counter(asyncUrl, input,transaction_id));
        get_call =  service.submit(new PathScanner(asyncUrl, input, transaction_id));
        
        try {     
            post_call.get();        
        } catch (ExecutionException ex) {
            Assert.fail();          
            ex.getCause().printStackTrace();  
        }
        try {
            get_call.get();
        } catch (ExecutionException ex) {
             Assert.fail();
             ex.getCause().printStackTrace();
                         
        }
    } catch (Exception ex) {
        ex.printStackTrace();
}
}

这是一个测试方法片段,测试用例也按预期失败,但在调用 Assert.fail() 后程序没有退出。

如果我删除了assert.fail(),那么程序就会成功终止……只是它没有显示任何失败。

请建议一种在调用 Assert.fail 后终止所有活动线程的方法。

标签: javamultithreadingexceptiontestngthreadpool

解决方案


要终止 Junit 4 上的任何测试,请在注释 超时时添加参数

@Test(timeout=2000)
public void testWithTimeout() {
  ...
}

或添加规则

@Rule
    public Timeout globalTimeout = Timeout.seconds(10); // 10 seconds max per method tested

六月 5

@Test
    @Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
    void failsIfExecutionTimeExceeds100Milliseconds() {
        // fails if execution time exceeds 100 milliseconds
    }

更多信息 JUnit 4测试超时

更多信息 JUnit 5测试超时


推荐阅读