【问题标题】:Mock a public static method with different return values模拟具有不同返回值的公共静态方法
【发布时间】: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"
}};

如何模拟一个公共静态方法并让它为同一个函数返回不同的值?

【问题讨论】:

标签: java jmockit


【解决方案1】:

在 Expectations 块中返回一个时间列表来完成这项工作。

ZonedDateTime instantExpected = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime secondInstant = instantExpected.plusHours(1L);
List<ZonedDateTime> allTimes = new ArrayList<ZonedDateTime>();
allTimes.add(instantExpected);
allTimes.add(instantExpected);
allTimes.add(secondInstant);
new Expectations(ZonedDateTime.class) {{
    ZonedDateTime.now(ZoneOffset.UTC);
    result = allTimes;
}};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多