EasyMock 期望方法在同一测试中返回多个不同的对象
我正在使用 EasyMock 对我的 Java 代码进行单元测试。我要测试的类是 RESTful Web 服务 API 层。该 API 有一个底层服务层,正在 API 测试中进行模拟。我的问题是弄清楚如何正确地对我的 editObject(ID, params...)
API 方法进行单元测试,因为它调用 service.getById()
两次并期望不同的值每次调用时返回的对象。
editObject(ID, params...)
首先尝试从服务层获取对象,以确保 ID 有效(首先调用 service.getById(ID)
期望,返回原始未修改的对象)。接下来,它修改 API 调用中指定的参数,将其保存到服务,并再次调用 get 将服务管理的修改对象交给调用者(第二个 service.getbyId(ID)
调用期望,返回修改后的对象)。
有没有办法用 EasyMock 来表示这一点?
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?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,您可以使用相同的方法和参数对两个方法调用执行两种不同的操作。只需按照您期望发生的顺序声明您的期望并相应地设置响应即可。
.once()
是可选的,但我发现在这种情况下它更具自我记录性。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.
The
.once()
is optional but I find in this case that it's more self-documenting.您可以链接多个
andReturn
方法调用:第一次使用
1
作为参数调用service.getById
时,模拟将返回firstObject< /code> 和第二次
secondObject
。您可以根据需要链接任意数量的链接,甚至可以通过andThrow
为特定调用抛出异常。You can chain multiple
andReturn
method calls:The first time
service.getById
is called with1
as argument the mock will returnfirstObject
and the second timesecondObject
. You can chain as many as you want and even throw an exception viaandThrow
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.