简体   繁体   English

如何模拟在 class java Z587FEFE304B8E3505DE89580432C?DZ25C 中初始化的新 object

[英]How to mock for new object initialized in a class java junit?

How to mock for new object initialized in a method of a class?如何模拟在 class 的方法中初始化的新 object? getting failure like "its failing like "Wanted but not invoked: invokeMyMethod() Actually, there were zero interactions with this mock.像“它像失败一样失败”想要但没有被调用:invokeMyMethod() 实际上,与这个模拟的交互为零。 ....." i have followed an example "https://stackoverflow.com/questions/5920153/test-class-with-a-new-call-in-it-with-mockito". its not helping. .....”我遵循了一个示例“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.
}

} }

You need PowerMock together with Mockito.您需要 PowerMock 和 Mockito。 But sadly it doesn't run with JUnit5.但遗憾的是它不能与 JUnit5 一起运行。 If you can run your test with JUnit 4 the answer of this question gives you a point to start from.如果您可以使用 JUnit 4 运行您的测试,那么这个问题的答案将为您提供一个起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM