不使用 Thread.sleep 的 JUnit 测试计划影响逻辑
JUnit Test scheduled impact logic without using Thread.sleep
我在我的代码中实现了一个 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 时间段内获取日志记录详细信息。这可以实施。另一种情况是我应该测试并确认在等待时间后,列表已清理并为空。
在你的情况下,我会分开 LogService
和 ScheduledAgent
的单元测试。
这样你就可以测试ScheduledAgent
的实际逻辑了。
另一种情况是,在 LogService
的测试中,您必须检查 scheduleAtFixedRate
方法是否 使用正确的参数调用 。为此,您可以使用一些库,例如 JMockit
或 PowerMockito
。您很可能需要将 timer
作为 class 的字段来实现模拟它的可能性。在我看来,您不需要定期测试 scheduleAtFixedRate
方法调用 provided TimerTask
,因为此方法来自 JDK 并且肯定已经被成千上万的开发人员测试过。
我在我的代码中实现了一个 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 时间段内获取日志记录详细信息。这可以实施。另一种情况是我应该测试并确认在等待时间后,列表已清理并为空。
在你的情况下,我会分开 LogService
和 ScheduledAgent
的单元测试。
这样你就可以测试ScheduledAgent
的实际逻辑了。
另一种情况是,在 LogService
的测试中,您必须检查 scheduleAtFixedRate
方法是否 使用正确的参数调用 。为此,您可以使用一些库,例如 JMockit
或 PowerMockito
。您很可能需要将 timer
作为 class 的字段来实现模拟它的可能性。在我看来,您不需要定期测试 scheduleAtFixedRate
方法调用 provided TimerTask
,因为此方法来自 JDK 并且肯定已经被成千上万的开发人员测试过。