views:

57

answers:

1

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());
+1  A: 

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