4

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());
Glide
  • 20,235
  • 26
  • 86
  • 135

3 Answers3

3

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

DoctorRuss
  • 1,429
  • 10
  • 9
  • So if I implement the equals method for User, could I then pass in my userMock, or will I have still have to use EasyMock.eq(mockUser) like you've suggested along with the implemented equals? – Glide Sep 22 '10 at 17:17
  • If the User equals method compares on the name (Bob), then creating the expected method via User mockUser = new User("Bob"); EasyMock.expect(userDaoMock.getPhone(EasyMock.eq(mockUser))).andReturn(new Phone()); should work – DoctorRuss Sep 23 '10 at 10:33
1

You can use

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

I think this should solve your problem.

Anthon
  • 69,918
  • 32
  • 186
  • 246
0

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.

manish
  • 69
  • 5