开发者

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

开发者 https://www.devze.com 2023-03-24 14:34 出处:网络
I am using EasyMock to unit test my Java code. The class I\'m trying to test is a RESTful webservice API layer. Th开发者_Python百科e API has an underlying service layer which is being mocked in the AP

I am using EasyMock to unit test my Java code. The class I'm trying to test is a RESTful webservice API layer. Th开发者_Python百科e 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?.


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.


You can chain multiple andReturn method calls:

EasyMock.expect(service.getById(1))
    .andReturn(firstObject)
    .andReturn(secondObject);

The first time service.getById is called with 1 as argument the mock will return firstObject and the second time secondObject. You can chain as many as you want and even throw an exception via andThrow for a specific call.


This technique is also helpful in conditional expressions in which you may want to invalidate the first condition but pass the second one or vice-a-versa.

0

精彩评论

暂无评论...
验证码 换一张
取 消