Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock expect method to return multiple, different objects in same test

I am using EasyMock to unit test my Java code. The class I'm trying to test is a RESTful webservice API layer. The API has an underlying service layer which is being mocked in the API test. My problem is figuring out how to correctly unit test my editObject(ID, params...) API method, since it calls service.getById() twice and expects a different object to be returned with each call.

editObject(ID, params...) first tries to grab the object from the service layer to make sure the ID is valid (first service.getById(ID) call to expect, returns original unmodified object). Next it modifies the parameters specified in the API call, saves it to the service, and calls get again to hand the caller the service-managed modified object (second service.getbyId(ID) call to expect, returns modified object).

Is there a way to represent this with EasyMock?.

like image 848
Amanda_A Avatar asked Aug 03 '11 01:08

Amanda_A


1 Answers

Sure, you can do two different things for two method calls with the same method and parameters. Just declare your expectations in the order you expect them to happen and set up the responses accordingly.

expect(mockService.getById(7)).andReturn(originalObject).once();
expect(mockService.getById(7)).andReturn(modifiedObject).once();
replay(mockService);

The .once() is optional but I find in this case that it's more self-documenting.

like image 146
Mark Peters Avatar answered Nov 10 '22 11:11

Mark Peters