开发者

Mock object creation inside a method

If I have the following method:

public void handleUser(String user) {

    User user = new User("Bob");
    Phone phon开发者_JS百科e = 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());


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".


You can use

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

I think this should solve your problem.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜