在进行模拟调用之前自动更新时间戳的最佳方法是什么?
这是我要测试的一些虚拟代码:
public class ThingWithATimestamp {
public Long timestamp;
public String name;
public ThingWithATimestamp(String name) {
this.name = name;
}
}
public class TheClassThatDoesStuff {
private ThingConnector connector;
public TheClassThatDoesStuff(ThingConnector connector) {
this.connector = connector;
}
public void updateTheThing(MyThingWithATimestamp thing) {
thing.timestamp = currentTimestamp();
connector.update(thing);
}
}
这是我要测试的内容:
public class TheClassThatDoesStuffTests {
@Test
public void canUpdateTheThing() {
ThingConnector connector = mock(ThingConnector.class);
TheClassThatDoesStuff doer = new ThisClassThatDoesStuff(connector);
doer.updateTheThing(new ThingWithATimestamp("the name"));
verify(connector, times(1)).update(SomeMatcherThatICantFigureOut);
}
我知道这段代码非常愚蠢,但我认为它准确地描述了我想要验证的内容。我基本上需要一个匹配器来填写测试,以验证时间戳是否在当前时间的 X 范围内,所以我知道它已正确更新,并且connector.update
使用对象的正确时间戳调用。