如果测试花费的时间超过定义的“超时”,则将抛出TestTimedOutException
并将测试标记为失败。 请参见以下示例:
PS已通过JUnit 4.12测试
1.超时示例
此timeout
示例仅适用于单个测试方法。 超时值以毫秒为单位。
TimeoutTest.java
package com.mkyong;
import org.junit.Test;
public class TimeoutTest {
//This test will always failed :)
@Test(timeout = 1000)
public void infinity() {
while (true) ;
}
//This test can't run more than 5 seconds, else failed
@Test(timeout = 5000)
public void testSlowMethod() {
//...
}
}
超时测试对于测试方法性能很有用。
2.全局超时规则示例
本示例说明如何创建全局超时规则,该规则将应用于类中的所有测试方法。
TimeoutTest.java
package com.mkyong;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.concurrent.TimeUnit;
public class TimeoutRuleTest {
//global timeout rule
@Rule
public Timeout globalTimeout = Timeout.seconds(1);
//This test will be failed, because it will take more than 1 second to finish!
@Test
public void testSlowMethod1() throws InterruptedException {
//...
TimeUnit.SECONDS.sleep(5000);
}
//passed
@Test
public void testSlowMethod2() {
//...
}
}
在上面的示例中,声明了全局Timeout
规则, testSlowMethod1()
和testSlowMethod2()
必须在1秒内完成测试,否则测试将失败。
PS该规则也适用于@Before
和@After
方法。
注意
所有单元测试都应该是快速的,并且此全局超时规则应该是您的最佳帮助。
参考文献
翻译自: https://mkyong.com/unittest/junit-4-tutorial-4-time-test/