更多: zhilu jiaocheng

JUnit 全局超时示例——超时规则

我们可以为一个类中的所有测试定义 JUnit 规则,而不是单独为所有测试指定超时属性。

@Rule
public Timeout globalTimeout = Timeout.seconds(2);
@Test 	//Pass
public void testInfiniteTametakingLoop1() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(1000);
	}
}
@Test 	//Fail
public void testInfiniteTametakingLoop2() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(5000);
	}
}

在上面的例子中,第一个测试将通过,而第二个测试将失败。

请注意,上述超时@Rule也适用于@Before@After方法。
所以请谨慎使用。

JUnit 测试超时示例 - 'timeout' 属性

要指定某个测试用例的超时时间,注释@Test中提到了“超时”属性。
例如,@Test(timeout = 1000)

超时时间以毫秒为单位指定。

@Test(timeout = 500)
public void testInfiniteTametakingLoop() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(1000);
	}
}

在上面的测试中,执行将在 5 秒后超时并显示以下消息。

java.lang.Exception: test timed out after 5000 milliseconds
如何为JUnit测试用例执行设置超时

JUnit 5 使用断言强制 超时

在 JUnit 5 中,我们可以使用断言强制测试超时。

import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.assertTimeout;
@Test
void timeoutNotExceeded() 
{
    //The following assertion succeeds.
    assertTimeout(ofMinutes(2), () -> {
        // Perform task that takes less than 2 minutes.
    });
}
@Test
void timeoutExceeded() 
{
    // The following assertion fails with an error message similar to:
    // execution exceeded timeout of 10 ms by 91 ms
    assertTimeout(ofMillis(10), () -> {
        // Simulate task that takes more than 10 ms.
        Thread.sleep(100);
    });
}
日期:2020-09-17 00:09:53 来源:oir作者:oir