gpt4 book ai didi

java - JUnit 不使用 Thread.sleep 测试计划的影响逻辑

转载 作者:行者123 更新时间:2023-12-01 09:11:39 25 4
gpt4 key购买 nike

我的代码中实现了一个 TimerTask。它定期对应用程序逻辑进行一些修改。现在我想使用 JUnit 测试这个 TimerTask 的影响。假设 TimerTask 计划每 2 秒运行一次,但我应该在不使用 Thread.sleep 的情况下运行测试用例。

public class LogService {

public LogService() {
configuration = ConfigurationUtil.getConfgiration();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new ScheduledAgent(), 0, configuration.getWaitTime());
}

private List<LoggingDetails> loggingDetails;

public List<LoggingDetails> getLoggers() {
return loggingDetails;

}

class ScheduledAgent extends TimerTask {

@Override
public void run() {
// if time has taken more than wait time, then clear loggingDetails

}
}
}

一个单元测试场景是我在 waitTime 时间段内获取loggingDetails。这个执行起来没问题。另一种情况是我应该测试并确认等待时间后,列表已清理且为空。

最佳答案

在您的情况下,我会将 LogServiceScheduledAgent 的单元测试分开。

因此,您将实现可以测试 ScheduledAgent 的实际逻辑。

另一种情况是,在您的 LogService 测试中,您必须检查 scheduleAtFixedRate 方法是否使用正确的参数调用。为此,您可以使用一些库,例如 JMockitPowerMockito。最有可能的是,您需要将计时器作为类的字段来实现模拟它的可能性。从我的角度来看,您不需要定期测试 scheduleAtFixedRate 方法是否正在调用提供的 TimerTask ,因为该方法来自 JDK 并且肯定已经经过了数千次测试开发人员。

关于java - JUnit 不使用 Thread.sleep 测试计划的影响逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882660/

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