【问题标题】:How to mock for new object initialized in a class java junit?如何模拟在类 java junit 中初始化的新对象?
【发布时间】: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 会很小心。你能帮忙换个方法吗?
  • 看看this answer

标签: java mockito junit5


【解决方案1】:

您需要 PowerMock 和 Mockito。但遗憾的是它不能与 JUnit5 一起运行。 如果您可以使用 JUnit 4 运行测试,this question 的答案会给您一个起点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多