gpt4 book ai didi

java - 如何模拟测试下方法调用的方法

转载 作者:行者123 更新时间:2023-12-02 03:11:31 25 4
gpt4 key购买 nike

我正在使用遗留代码,并希望增加它的测试覆盖率。

我有一个类:

public class MyStrategy implements SomeStrategy {

TimeAndDateUtils timeAndDateUtils = new TimeAndDateUtils();

@Override
public boolean shouldBeExtracted(Argument argument) {
Date currentDate = timeAndDateUtils.getCurrentDate();
return currentDate.isBefore(argument.getDate());
}

}

我想测试 shouldBeExtracted-Method 并模拟对 timeAndDateUtils.getCurrentDate() 的调用,以便它返回一些固定值。

所以我想做的是:

Date currentDate = %some fixed date%
TimeAndDateUtils timeAndDateUtils = Mockito.mock(TimeAndDateUtils.class);
Mockito.when(timeAndDateUtils.getCurrentDate()).thenReturn(currentDate);
Assert.assertTrue(myStrategy.shouldBeExtracted(argument))

如何强制 MyStrategy-Class 使用模拟对象而不是创建自己的对象?

最佳答案

您可以使用反射将模拟放入 MyStrategy 对象中。它看起来像这样:

MyStrategy myStrategy = new MyStrategy(); // I don't know if you are using DI
MyStrategy.class.getDeclaredField("timeAndDateUtils").set(myStrategy, timeAndDateUtilsMock);

关于java - 如何模拟测试下方法调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40973022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com