[英]How to set timeout at runtime in JUnit Test Case
I am using JUnit v4
as a test framework. 我正在使用JUnit v4
作为测试框架。 I wanted to know how to set timeout at runtime in Test Case? 我想知道如何在测试用例中在运行时设置超时?
I am using Parameterized
test. 我正在使用Parameterized
测试。 In which I have a list of Scenario
, which contains timeout value and some other fileds. 在其中,我有一个Scenario
列表,其中包含超时值和一些其他字段。 Each of these Scenario
may have different-2 timeouts. 这些Scenario
每一个都可能具有不同的2个超时。
The timeout
parameter is not helping me to achieve this. 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
}
Please help me to fine out any alternative to set the timeout dynamically. 请帮助我完善所有替代方法以动态设置超时。
I think, you need to build it yourself, like: 我认为,您需要自己构建它,例如:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.