使用反射设置JUNIT测试超时



我到目前为止找到了两种设置Junit测试超时的方法。要么使用:

@Test(timeout=XXX)

或使用:

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

就我而言,我有一个测试跑步者作为主要类来运行所有测试套件,因此我可以作为可执行的JAR执行测试。我希望这位跑步者使用反射来设置超时。

可以做吗?

您可以将超时功能添加到So:

之类的自定义测试跑者
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 ...

最新更新