如何使用 Moq 存根抽象集合?
假设我有这个类:
public abstract class CustomerCollectionBase : Collection<Customer>{}
我的一个正在测试的类接受 CustomerCollectionBase 实例(它将是某个子类)。在测试的方法中,通过 for 循环枚举该集合,并检查和处理结果。 如下所示:
for (int i=0;i<_customers.Count; i++){
//process customer
}
是否可以使用 Moq 存根这个集合,以便我可以将存根作为依赖项传递给我的被测类的构造函数?
谢谢。
Let's say I have this class:
public abstract class CustomerCollectionBase : Collection<Customer>{}
One of my classes under test accepts CustomerCollectionBase instance (it will be some subclass). In the method under test, this collection is enumerated via for loop and results are examined and processed.
like follows:
for (int i=0;i<_customers.Count; i++){
//process customer
}
Is it possible to stub this collection with Moq so I could pass stub as a dependency to my class-under-test's constructor?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从技术上讲,这是可能的,但很困难,因为
Collection
中唯一可重写的成员受到保护。传递一个具体的集合会容易得多,除非您绝对必须对集合本身执行一些基于交互的测试。
但是,如果您必须使用 Moq 执行此操作,则首先需要将以下 using 指令添加到测试代码中:
您现在可以使用 Protected() 方法将模拟设置为 CustomerCollectionBase 的适当受保护虚拟方法。
有关详细信息,请参阅此博文如何使用最小起订量模拟受保护的成员。
Technically, this would be possible, but difficult, since the only overridable members of
Collection<T>
are protected.It would be much easier to just pass a concrete collection instead, unless you absolutely must perform some interaction-based testing on the collection itself.
However, if you must do this with Moq, you will first need to add the following using directive to your test code:
You can now use the Protected() methods to setup the mock to with the appropriate protected virtual methods of CustomerCollectionBase.
See this blog post for more information on how to Mock protected members with Moq.