如何在JUnit测试用例中设置运行时超时

ctehm74n  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(116)

我正在使用JUnit v4作为测试框架。我想知道如何在测试用例中设置运行时超时?
我正在使用一个Parameterized测试,其中我有一个Scenario s的列表,其中包含超时值和一些其他字段。每个Scenario s可能有不同的超时。
timeout参数不能帮助我实现这一点。

@Test(timeout = getTimeOut())
public void secureLoginWithLongUsername() {
    // Test case goes here

}

private final long getTimeOut() {
    // I am doing some processing here to calculate timeOut dynamically
    long timeOut = scenario.getTimeOut();
    return timeOut;
}

@Parameters
public static Collection<Scenario[]> getParameters() {

    List<Scenario[]> scenarioList = new ArrayList<Scenario[]>();
    Configuration config = new Configuration();
    List<Scenario> scenarios = config.getScenarios();
    for (Scenario scenario : scenarios) {
        scenarioList.add(new Scenario[] { scenario });
    }

    return scenarioList;
}

public class Configuration {
    private List<Scenario>   scenarios;
    //Some processing here
    public List<Scenario> getScenarios() {
        return scenarios;
    }
}

public class Scenario {
    private long   timeOut;
    private String   name;
    //Some more fields here
}

字符串
请帮助我找到一个替代动态设置超时。

wqnecbli

wqnecbli1#

我觉得,你需要自己动手,比如:

private Timer timer;

@After
public void terminateTimeout() {
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}

@Test
public void testTimeout() throws Exception {
    setTimeout(1000);
    // run test...
}

private void setTimeout(int duration) {
    final Thread currentThread = Thread.currentThread();
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            currentThread.interrupt();
        }
    }, duration);
}

字符串

3df52oht

3df52oht2#

基于Moritz Petersen's answer, with simplification for a single test, and creating a test failure instead of an error

@Test
public void secureLoginWithLongUsername() {
  final Thread currentThread = Thread.currentThread();
  ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  Future<?> timeout = scheduler.schedule(() -> currentThread.interrupt(), getTimeOut(), TimeUnit.SECONDS);
  try
  {
    // Test case goes here
  }
  catch (InterruptedException exception)
  {
     fail("thread was interrupted", exception);
  }
  timeout.cancel(true);
}

字符串

相关问题