java - 使用反射设置 JUnit 测试超时

标签 java reflection junit timeout

到目前为止,我已经找到了 2 种设置 JUnit 测试超时的方法。要么使用:

@Test(timeout=XXX)

或者使用类似的东西:

@ClassRule
public static Timeout timeoutRule = new Timeout(XXX, TimeUnit.MILLISECONDS);

就我而言,我有一个测试运行程序作为主类来运行我的所有测试套件,因此我可以将测试作为可执行 jar 来执行。 我希望这个运行程序使用反射动态地设置超时。

可以吗?

最佳答案

您可以将超时功能添加到自定义测试运行程序,如下所示:

public class TimeoutTestRunner extends BlockJUnit4ClassRunner {

    public TimeoutTestRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected Statement withPotentialTimeout(FrameworkMethod method, Object test, Statement next) {
        return FailOnTimeout.builder()
                // you'll probably want to configure/inject this value rather than hardcode it ...
                .withTimeout(1, TimeUnit.MILLISECONDS)
                .build(next);
    }
}

使用此测试运行程序在以下测试用例中进行测试...

@RunWith(TimeoutTestRunner.class)
public class YourTest {

    @Test
    public void willTimeout() throws InterruptedException {
        Thread.sleep(50);
        assertTrue(true);
    }

    @Test
    public void willNotTimeout() throws InterruptedException {
        assertTrue(true);
    }
}

...将表现如下:

  • willTimeout : 将失败并显示 TestTimedOutException
  • willNotTimeout : 会通过

尽管您需要通过此运行程序运行测试,但您将能够从一个位置控制其超时设置并提供自定义超时派生策略,例如 if test name matches <some regex> then timeout is x else ... .

关于java - 使用反射设置 JUnit 测试超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058160/

相关文章:

java - Eclipse Java switch-case 失败警告

c# - 将过滤器字符串转换为 C# 委托(delegate)

unit-testing - 如何从默认 "maven test"和 eclipse "run as junit test"中排除特定的单元测试

android - Jelly Bean 中的飞行模式

asp.net-mvc - 如何获取已应用于特定 Controller 操作的授权过滤器列表?

Java:这个进程分配了多少内存?

java - 断言字符串列表包含忽略大小写的字符串

java - java中的骰子求和应用程序。我遇到索引错误并且我设计了错误的代码但我不知道在哪里

java - 如何测试方法返回类型是否匹配 List<String>

java - JDBC : Operation not allowed after ResultSet closed