@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);
}
1.使用静态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);
}
@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);
}
EDIT:最近不赞成使用超时来使用此初始化
@Rule
public Timeout timeout = new Timeout(120000, TimeUnit.MILLISECONDS);
3条答案
按热度按时间ujv3wf0j1#
因为答案没有提供例子,所以重提一个老问题。
您可以指定超时
1.根据试验方法:
1.对于使用
Timeout
@Rule
的测试类中的所有方法:1.使用静态
Timeout
@ClassRule
在全局范围内运行类中所有测试方法的总时间:1.甚至将超时(
@Rule
或@ClassRule
)应用于all classes in your entire suite:EDIT:最近不赞成使用超时来使用此初始化
您现在应该提供时间单位,因为这将为您的代码提供更多的粒度。
xmd2e60i2#
如果您使用JUnit 4和
@Test
,您可以指定timeout
参数,该参数将使花费时间比指定时间更长的测试失败。一个可能更好的替代方法是使用
@Rule
和org.junit.rules.Timeout
。这样,您可以针对每个类(甚至在共享超类中)执行此操作。sz81bmfz3#
我从标签中知道这个问题是针对JUnit 4的,但是在JUnit 5(Jupiter)中,mechanism has changed。
来自指南:
(The
unit
的默认值为秒,因此您可以直接使用@Timeout(1)
。)很容易在整个课程中应用一次:
要将相同的超时应用于测试类及其所有@Nested类中的所有测试方法,可以在类级别声明@Timeout注解。
出于您的目的,您甚至可以在构建作业上试验顶级配置:
“junit.jupiter.执行.超时.测试.方法.默认值”
@测试方法的默认超时