Creating a wet object inside a method

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 test this with mocks using EasyMock, is there anyway, I can check the User parameter that I passed to my UserDao code as follows:

 User user = new User("Bob"); EasyMock.expect(userDaoMock.getPhone(user)).andReturn(new Phone()); 

When I tried to run the above test, it complains about an unexpected method call, which I assume, because the actual user created in the method does not match the one I pass in ... Am I right about that?

Or the most stringent way to check the parameter I pass to UserDao:

 EasyMock.expect(userDaoMock.getPhone(EasyMock.isA(User.class))).andReturn(new Phone()); 
+4
source share
3 answers

You are correct that an unexpected method call is called because the User object is different from the expected and actual getPhone calls.

As @ laurence-gonsalves notes in a comment, if User has a useful equals method, you can use EasyMock.eq(mockUser) inside the expected getPhone call, which should check that these two User objects are equal.

See the EasyMock documentation , in particular in the Flexible Expectations with Compliance Arguments section.

+3
source

you can use

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

I think this should solve your problem.

+1
source

Minor change in answer given by Yeswanth Devisetty

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

This will solve the problem.

0
source

All Articles