在Java中单元测试基于时间的逻辑 [英] Unit testing time-based logic in Java
问题描述
我有一种方法可以根据当前日期是从数据库中获取的数据实现不同的逻辑。
I have a method which implements different logic on data fetched from a DB depending on what the current date is.
我想通过单元测试创建对象进行测试,将其保存在DB中并调用测试方法。然而,为了获得可预测的结果,我需要每次更改系统日期,我不知道如何在Java中执行此操作。
I want to test it by having the unit test create objects, save them in the DB and invoke the tested method. However, in order to have predictable results I need to change the system date each time and I don't know how to do that in Java.
建议?
推荐答案
您可以使用当前日期生成预期结果。
You can generate your expected results using the current date.
或者你写你的系统使用一个日期/时间,当你被测试时(而不是时钟)这样的时间总是测试期望。
Or you write your system to use a date/time you give it when being tested (rather than the clock) That way the time is always what the test expects.
我使用的东西像
interface TimeSource {
long currentTimeMS(); // actually I have currentTimeNS
void currentTimeMS(long currentTimeMS);
}
enum VanillaTimeSource implements TimeSource {
INSTANCE;
@Override
public long currentTimeMS() {
return System.currentTimeMillis();
}
@Override
public void currentTimeMS(long currentTimeMS) {
// ignored
}
}
class FixedTimeSource implements TimeSource {
private long currentTimeMS;
@Override
public long currentTimeMS() {
return currentTimeMS;
}
@Override
public void currentTimeMS(long currentTimeMS) {
this.currentTimeMS = currentTimeMS;
}
}
在测试中,我使用了一个可以数据驱动的FixedTimeSource例如由输入/事件设置。在生产中,我使用的是VanillaTimeSource.INSTANCE,它忽略了输入/事件中的时间,并使用当前时间。
In tests I use a FixedTimeSource which can be data driven e.g. set by inputs/events. In production I use a VanillaTimeSource.INSTANCE which ignores times in inputs/events and uses the current time.
这篇关于在Java中单元测试基于时间的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!