Glide
Glide

Reputation: 21245

Mock object creation 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'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());

Upvotes: 4

Views: 7306

Answers (3)

manish
manish

Reputation: 69

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.

Upvotes: 0

Yeswanth Devisetty
Yeswanth Devisetty

Reputation: 31

You can use

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

I think this should solve your problem.

Upvotes: 1

DoctorRuss
DoctorRuss

Reputation: 1439

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

Upvotes: 3

Related Questions