代码之家  ›  专栏  ›  技术社区  ›  Valentin V

如何使用Moq存根抽象集合?

  •  3
  • Valentin V  · 技术社区  · 16 年前

    public abstract class CustomerCollectionBase : Collection<Customer>{}
    

    我测试的一个类接受CustomerCollectionBase实例(它将是某个子类)。在测试的方法中,通过for循环枚举此集合,并检查和处理结果。 具体如下:

    for (int i=0;i<_customers.Count; i++){
     //process customer
    }
    

    非常感谢。

    1 回复  |  直到 15 年前
        1
  •  3
  •   Mark Seemann    16 年前

    从技术上讲,这是可能的,但很困难,因为 Collection<T> 他们受到保护。

    只传递一个具体的集合要容易得多,除非你完全同意

    但是,如果必须使用Moq执行此操作,则首先需要将以下using指令添加到测试代码中:

    using Moq.Protected;
    

    现在,您可以使用Protected()方法使用CustomerCollectionBase的相应受保护虚拟方法设置模拟。

    看见 this blog post 有关如何使用Moq模拟受保护成员的详细信息。

    推荐文章