【问题标题】:Java program does not terminate after Assert.fail()Java 程序在 Assert.fail() 之后没有终止
【发布时间】:2020-07-09 19:31:24
【问题描述】:

我有一个 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();
}
}

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

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

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

【问题讨论】:

  • 为什么不在 assert.fail() 之前关闭它们?。
  • 您好,欢迎来到 stackoverflow!你能看看你的问题修复错别字并格式化你的代码吗?这将使其他人更容易理解您的要求。否则你的问题很可能会被否决。

标签: java multithreading exception testng threadpool


【解决方案1】:

要终止 Junit 4 上的任何测试,请在注释 timeout

上添加参数
@Test(timeout=2000)
public void testWithTimeout() {
  ...
}

或者添加规则

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

对于 Junit 5

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

更多信息 JUnit 4 Timeout for tests

更多信息 JUnit 5 Timeout for tests

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多