我想测试一个方法,它获取一个带有信息作为参数的对象:
//mocking a user object with some random data
User user createMockUser(loginName, firstName, lastName, salutation, company, mailAddress);
//do something with that user object
foo(user);
并且测试的重点是测试 foo(user)。
使用 createMockUser() 的这些变体:
使用 when 函数:
protected User createMockUser(String loginName, String firstName,
String lastName, String salutation, String mailAddress)
{
User user = Mockito.mock(User.class);
Mockito.when(user.getLoginName()).thenReturn(id);
Mockito.when(user.getFirstName()).thenReturn(firstName);
Mockito.when(user.getLastName()).thenReturn(lastName);
Mockito.when(user.getSalutation()).thenReturn(salutation);
Mockito.when(user.getMailAddress()).thenReturn(mailAddress);
return user;
}
使用间谍:
protected User createMockUser(String loginName, String firstName,
String lastName, String salutation, String mailAddress)
{
User spyUser = spy(new User());
spyUser.setLoginName(loginName);
spyUser.setFirstName(firstName);
spyUser.setLastName(lastName);
spyUser.setSalutation(salutation);
Mockito.when(spyUser.getMailAddress()).thenReturn(mailAddress);
return spyUser;
}
这根本行不通:
protected User createMockUser(String loginName, String firstName,
String lastName, String salutation, String mailAddress)
{
User user;
user = Mockito.mock(User.class);
user.setLoginName(loginName);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setSalutation(salutation);
Mockito.when(user.getMailAddress()).thenReturn(mailAddress);
return user;
}
我仍然是 mockito 的新手,但据我所知,spy 确实使用对象的方法来获取对象中的值,并且何时调用 get 函数来返回 mock 中指示的内容。但是对于这个测试,它们的结果基本相同,因为我只想测试 foo. 那么,哪一个会更好,还是有更优雅的方式?