【发布时间】:2022-01-19 11:02:58
【问题描述】:
如何模拟在类的方法中初始化的新对象?像“它像失败一样失败”想要但没有被调用:invokeMyMethod() 实际上,与这个模拟的交互为零。 ......”我已经跟着 一个示例“https://stackoverflow.com/questions/5920153/test-class-with-a-new-call-in-it-with-mockito”。它没有帮助。
Class Login { //existing design. cannot change.
private MyClass myclass;
public void init() {
myclass = new MyClass();
myclass.invokeMyMethod();
}
}
///Junit
@ExtendWith(MockitoExtension.class)
class LoginTest {
@InjectMocks
Login login;
@Test
void testInit() {
Login spyObj = Mockito.spy(login);
MyClass myclass = Mockito.mock(MyClass.class);
spyObj.init();
verify(myclass).invokeMyMethod();// its failing like "Wanted but not invoked: invokeMyMethod() Actually,
//there were zero interactions with this mock.
}
}
【问题讨论】:
-
您正在模拟的“myClass”与在 init() 中初始化的“myClass”不同。您无法访问它。您需要找到一种方法将“myClass”注入登录。二传手怎么样?
-
现有设计。所以无法改变它。 Thatswat 我看到我们可以使用 spy 。但这也行不通。
-
您需要找到一种方法来用您的模拟对象替换使用
new MyClass()实例化的“myClass”。否则,就没有希望验证它的交互了。 -
但是在这个例子中 "stackoverflow.com/questions/5920153/…" ,使用 spy 会很小心。你能帮忙换个方法吗?