在方法内创建模拟对象
如果我有以下方法:
public void handleUser(String user) {
User user = new User("Bob");
Phone phone = userDao.getPhone(user);
//something else
}
当我使用 EasyMock 进行模拟测试时,我是否可以像这样测试传递到 UserDao 模拟中的 User 参数:
User user = new User("Bob");
EasyMock.expect(userDaoMock.getPhone(user)).andReturn(new Phone());
当我尝试运行上述测试时,它会抱怨意外的方法调用我假设是因为该方法中创建的实际用户与我传入的用户不同......我对此是否正确?
或者我可以测试传递给 UserDao 的参数的最严格方法就是:
EasyMock.expect(userDaoMock.getPhone(EasyMock.isA(User.class))).andReturn(new Phone());
If I have the following method:
public void handleUser(String user) {
User user = new User("Bob");
Phone phone = userDao.getPhone(user);
//something else
}
When I'm testing this with mocks using EasyMock, is there anyway I could test the User parameter I passing into my UserDao mock like this:
User user = new User("Bob");
EasyMock.expect(userDaoMock.getPhone(user)).andReturn(new Phone());
When I tried to run the above test, it complains about unexpected method call which I assume because the actualy User created in the method is not the same as the one I'm passing in...am I correct about that?
Or is the strictest way I could test the parameter I'm passing into UserDao is just:
EasyMock.expect(userDaoMock.getPhone(EasyMock.isA(User.class))).andReturn(new Phone());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抛出意外的方法调用是正确的,因为
User
对象在对getPhone
的预期调用和实际调用之间是不同的。正如 @laurence-gonsalves 在评论中提到的,如果
User
有一个有用的equals
方法,您可以在预期对getPhone
的调用应检查两个User
对象是否相等。查看 EasyMock 文档,特别是“参数匹配器的灵活期望”部分。
You are correct that the unexpected method call is being thrown because the
User
object is different between the expected and actual calls togetPhone
.As @laurence-gonsalves mentions in the comment, if
User
has a usefulequals
method, you could useEasyMock.eq(mockUser)
inside the expected call togetPhone
which should check that it the twoUser
object are equal.Have a look at the EasyMock Documentation, specifically in the section "Flexible Expectations with Argument Matchers".
您可以使用
我认为这应该可以解决您的问题。
You can use
I think this should solve your problem.
Yeswanth Devisetty 给出的答案稍作修改
EasyMock.expect(userDaoMock.getPhone(EasyMock.anyObject(User.class))).andReturn(new Phone());
这将解决问题。
A little change in the answer given by Yeswanth Devisetty
EasyMock.expect(userDaoMock.getPhone(EasyMock.anyObject(User.class))).andReturn(new Phone());
This will solve the problem.