如何模拟依赖于更新可变对象的方法
我有一个不返回值的方法。相反,它接受一个列表并修改该列表的成员。显然,列表本身是可变的,它的成员也是如此。
EG:我想嘲笑这个:
void modifyRequests(List<MutableObject> requests);
I have a method which doesn't return a value. It instead accepts a list and modifies the members of this list. Obviously the list itself is mutable, as are its members.
EG: I want to mock this:
void modifyRequests(List<MutableObject> requests);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,各种模拟框架确实提供了执行此操作的方法(在调用方法时执行使用参数的自定义操作) - 但我强烈考虑不使用模拟。除非您真的想验证被测类与其协作者之间的协议,否则您应该考虑编写一个假的而不是模拟的。然后,您可以使假冒的行为随您的喜好而变化 - 通常(IME)您最终会得到更简单的测试代码。
它并不总是合适的,并且嘲笑当然有它的一席之地 - 但随着时间的推移,我发现一个写得好的假货是有价值的,特别是当它是许多类使用的依赖项时。
Well, various mocking frameworks do provide ways of doing this (executing custom actions which use the parameters when a method is invoked) - but I would strongly consider not using mocking. Unless you really want to validate the protocol between your class-under-test and its collaborators, you should consider writing a fake instead of a mock. Then you can make the fake behave however you like - and typically (IME) you end up with simpler test code.
It's not always appropriate, and mocking certainly has its place - but over time I've found that a well-written fake can be worth its weight in gold, particularly if it's a dependency used by many classes.
使用 Mockito (我猜其他模拟框架也可以做到这一点):
丑陋,你不觉得吗?我强烈建议提取这个匿名内部类并对其进行描述性命名。我强烈建议重构您的代码并简单地返回
List; requests
(或者可能返回修改后的副本 - 传递要修改的对象有点笨拙)。With Mockito (I guess other mocking frameworks can do this as well):
Ugly, don't you think? I strongly recommend extracting this anonymous inner class and naming it descriptively. I recommend even stronger to refactor your code and simply return the
List<MutableObject> requests
(or maybe return modified copy - passing objects to be modified is a bit clumsy).如果您正在模拟该方法,为什么使用该方法的代码需要知道对
modifyRequests()
的调用是否更改了任何内容?换句话说,您应该能够将此方法模拟为无操作,并且调用它的代码仍应具有相同的功能。
否则,调用此方法的代码和方法本身耦合得太紧密。
If you are mocking that method, why does the code using that method need to know if the call to
modifyRequests()
changed anything?In other words, you should be able to mock this method as a no-op and the code calling it should still function the same.
Otherwise, the code calling this method and the method itself are too tightly coupled.