在方法内创建模拟对象

发布于 2024-09-24 02:13:27 字数 594 浏览 5 评论 0原文

如果我有以下方法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情域 2024-10-01 02:13:27

抛出意外的方法调用是正确的,因为 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 to getPhone.

As @laurence-gonsalves mentions in the comment, if User has a useful equals method, you could use EasyMock.eq(mockUser) inside the expected call to getPhone which should check that it the two User object are equal.

Have a look at the EasyMock Documentation, specifically in the section "Flexible Expectations with Argument Matchers".

时光瘦了 2024-10-01 02:13:27

您可以使用

EasyMock.expect(userDaoMock.getPhone(EasyMock.anyObject())).andReturn(new Phone());

我认为这应该可以解决您的问题。

You can use

EasyMock.expect(userDaoMock.getPhone(EasyMock.anyObject())).andReturn(new Phone());

I think this should solve your problem.

只怪假的太真实 2024-10-01 02:13:27

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文