我有一个这样的:
class User {
String name;
}
class Contacts {
User getUser() {
return new User();
}
}
我这样做是为了在我的测试中我可以模拟这样的方法:
@ExtendWith(MockitoExtension.class)
class ContactsTest {
@Spy
private Contacts sut;
@Mock
private User user;
@Test
void testSomething() {
doReturn(user).when(sut).getUser();
}
@Test
void testGetUser() {
// verify(new User(), times(1));
// verify(user, times(1));
}
}
我如何测试 testGetUser
?
我上面评论的仅有的两个想法给了我这些错误:
对于第一个:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type User and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();
第二个
org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
答案 0 :(得分:1)
首先,由于您的被测单元是 Contacts
类,因此无需对其进行 spy
并模拟其行为,因为这是您需要测试的类。所以,我会继续删除它。
现在关于您的问题,您需要测试的是 getUser
的实际结果,因此所有测试中最简单的就是在 Contacts
的实例上调用该方法并断言返回的结果是 non-null
对象的 User
实例。
如果您真的想测试 User
类的构造函数是否被调用,您将需要使用 PowerMock
来实际模拟该调用(建议反对并且很可能甚至不起作用使用 JUnit5) 或使用 mockito-inline
。
一旦完成,您就可以从构造函数调用返回一个模拟的 User
实例,然后您可以在该实例上运行断言。