Mif*_*eet 15
由于答案没有提供一个例子,因此重新提出一个旧问题.
您可以指定超时
每种测试方法:
@Test(timeout = 100) // Exception: test timed out after 100 milliseconds
public void test1() throws Exception {
Thread.sleep(200);
}
Run Code Online (Sandbox Code Playgroud)对于测试类中的所有方法,使用Timeout
@Rule
:
@Rule
public Timeout timeout = new Timeout(100);
@Test // Exception: test timed out after 100 milliseconds
public void methodTimeout() throws Exception {
Thread.sleep(200);
}
@Test
public void methodInTime() throws Exception {
Thread.sleep(50);
}
Run Code Online (Sandbox Code Playgroud)全局使用静态运行类中所有测试方法的总时间Timeout
@ClassRule
:
@ClassRule
public static Timeout classTimeout = new Timeout(200);
@Test
public void test1() throws Exception {
Thread.sleep(150);
}
@Test // InterruptedException: sleep interrupted
public void test2() throws Exception {
Thread.sleep(100);
}
Run Code Online (Sandbox Code Playgroud)甚至对整个套件中的所有类应用超时(@Rule
或者@ClassRule
):
@RunWith(Suite.class)
@SuiteClasses({ Test1.class, Test2.class})
public class SuiteWithTimeout {
@ClassRule
public static Timeout classTimeout = new Timeout(1000);
@Rule
public Timeout timeout = new Timeout(100);
}
Run Code Online (Sandbox Code Playgroud)编辑:最近不推荐使用超时来利用此初始化
@Rule
public Timeout timeout = new Timeout(120000, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
您现在应该提供Timeunit,因为这将为您的代码提供更多粒度.
如果使用JUnit 4 @Test
,则可以指定使timeout
测试时间超过指定时间的参数失败的参数.缺点是你必须将它添加到每个测试方法中.
一个可能更好的选择是使用@Rule
with org.junit.rules.Timeout
.有了这个,你可以按类(甚至在共享的超类)中完成.