gpt4 book ai didi

java - 如果部分测试花费的时间太长,如何从 JUnit 测试返回到 main 方法

转载 作者:行者123 更新时间:2023-11-28 21:11:08 25 4
gpt4 key购买 nike

我尝试从我的 main() 方法运行 junit:

public static void main(String... args) throws ClassNotFoundException, 
IOException {
//...
logger.debug("className " + className + "methodName " + methodName);

Request request = Request.method(Class.forName(className), methodName);
return new JUnitCore().run(request);
}

我有一个包含 10 个命令的 E2E 测试(比方说)。它由 JUnit 运行,我想将命令 3-5 的运行时间限制为 X 毫秒(其中 X 在运行时确定)。如果它运行的时间超过 X,我想返回到 main() 并打印一些东西。

我试过 System.exit() 但它关闭了整个应用程序。我试过了:

public void setTimeOut(String criticalBlockTimeOutMilli) {
if (criticalBlockTimeOutMilli != null) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
E2eResult e2eResult = E2eResult.getInstance();
e2eResult.status = E2eStatus.TIMEOUT;
//System.exit(2);
}
};
new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOutMilli));
}
}

public void setTimeOut(final Thread thread, String criticalBlockTimeOutMilli) {
if (criticalBlockTimeOutMilli != null) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
E2eResult e2eResult = E2eResult.getInstance();
e2eResult.status = E2eStatus.TIMEOUT;
thread.interrupt();
}
};
new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOutMilli));
}
}

但即使超过限制,主线程仍会继续运行测试。你有什么建议?

最佳答案

单元测试可能不是解决此类性能测试的最佳方法。但是,如果出于某种原因必须这样做,请继续阅读...

使用一个 ExecutorService 来运行你想要的命令,在给定的超时时间内。如果超时到期,抛出您可以在主线程中捕获的自己的异常:

@Test
public void yourTest() throws Exception {

// Do commands 1-2

ExecutorService service = Executors.newSingleThreadExecutor();
Future<Void> result = service.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
// call commands 3-5
return null;
}
});

try {
result.get(42, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new YourOwnException();
}

service.shutdown();

// Do commands 6-10
}

关于java - 如果部分测试花费的时间太长,如何从 JUnit 测试返回到 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27507498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com