模拟 (Moq) 对象列表 - 最佳实践/简化
请考虑以下事项:
new SUT(null, null, new List<IObjectBeingMocked>() { mockObjectOne.Object, mockObjectTwo.Object })
我的 SUT(被测系统)需要一个对象列表作为第三个参数。这些需要是模拟,因为我对它们设定了一些期望。
我该如何清理它,以便无需在列表中的每个项目上调用 .Object
?通常只有两个项目,但这个项目可能会增加,在我看来,这会使测试更难阅读。
轻松/良好地将模拟对象列表转换为实际对象的最佳方法是什么?
Consider the following:
new SUT(null, null, new List<IObjectBeingMocked>() { mockObjectOne.Object, mockObjectTwo.Object })
My SUT (System Under Test) needs a list of objects as the third parameter. These need to be mocks as I've set some expectatioins on these.
How would I clear it up so that I can remove the need to call .Object
on each item in the list? There are only two items usually but this could grow and in my opinion this makes the test harder to read.
What would be the best way of transforming this list of mock objects into actual objects easily/nicely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您可以使用扩展方法来管理列表创建和对象属性的调用。
Perhaps you could use extension methods to manage the list creation and invocation of the Object property for you.
处理此问题的一个好方法是创建一个 GetSUT() 方法,该方法仅在一个位置创建一次。然后,当您的 SUT 创建发生变化时,您只需在一处进行更改。
A good way to handle this is to create a GetSUT() method that creates it only once in one place. Then as your SUT creation changes, you only have to change it in one place.
您可以使用 Mocks.Query() 方法,该方法将返回所有模拟 SUT 实例的集合。
此功能存在于最小起订量的测试版中。请参阅此处了解详细信息:
You can use Mocks.Query() method which will return a collection of all mocked SUT instances.
This feature exists in the beta version of moq. See the details here:
为了清楚起见,您可以引入解释变量(局部变量):
编辑:也许有更好的选择名称比我的“objectOne”、“objectTwo”。 ;)
You could introduce explaining variables (locals) for clarity:
EDIT: Perhaps with better-chosen names than my "objectOne", "objectTwo". ;)