【发布时间】:2021-08-06 15:54:37
【问题描述】:
此代码应该检查是否已经过了一个小时,然后执行特定操作。为了模仿这一点,我在 JMockit 中模拟 ZonedDateTime 类,并希望它的 now 方法 (ZonedDateTime.now(ZoneOffset.UTC);) 在我的代码执行期间返回两个不同的值。我的第一次尝试涉及以下静态方法的模拟实现:
ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
new Expectations(ZonedDateTime.class) {{
ZonedDateTime.now(ZoneOffset.UTC);
result = instantExpected;
}};
上面的代码确保每次调用函数时都返回相同的瞬间,但它不允许我在一定次数的函数调用后更改值。我想要类似于下面代码应该如何工作的东西。
ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
new Expectations(ZonedDateTime.class) {{
ZonedDateTime.now(ZoneOffset.UTC);
result = instantExpected;
times = 2; // the first two times it should return this value for "now"
ZonedDateTime.now(ZoneOffset.UTC);
result = instantExpected.plusHours(1L);
times = 1; // the third time it should return this new value for "now"
}};
如何模拟一个公共静态方法并让它为同一个函数返回不同的值?
【问题讨论】:
-
更好的选择是将时钟传递给获取时间的方法。时钟有一个可以注入的称为 FixedClock 的存根实现。见stackoverflow.com/a/51525990/217324
-
感谢您的来信。供将来参考,这里有一个链接,用于按照您的描述在 Java 中模拟时钟:stackoverflow.com/questions/32792000/…