如何使用moq模拟私有只读IList <T>属性

epz*_*zee 2 c# moq nbuilder

我试图模仿这个列表:

private readonly IList<MyClass> myList = new List<MyClass>();
Run Code Online (Sandbox Code Playgroud)

使用这个(如看到这里):

IList<MyClass> mockList = Builder<MyClass>.CreateListOfSize(5).Build();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(stakeHoldersList);
Run Code Online (Sandbox Code Playgroud)

但是在运行时我得到一个InvalidCastException:

Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

jas*_*son 6

好吧,我认为模拟一个私有的实现细节是奇怪和坦率的错误.您的测试不应该依赖于私有实现细节.

但是,如果我是你,我会这样做的方法是添加一个构造函数:

public Foo {
    private readonly IList<MyClass> myList;
    public Foo(IList<MyClass> myList) { this.myList = myList; }
}
Run Code Online (Sandbox Code Playgroud)

然后使用Moq模拟一个实例IList<MyClass>并通过构造函数传递它.

如果你不喜欢这个建议,或者做一个虚拟财产:

public Foo {
    private readonly IList<MyClass> myList = new MyList();
    public virtual IList<MyClass> MyList { get { return this.myList; } }
}
Run Code Online (Sandbox Code Playgroud)

然后使用Moq覆盖该属性.

不过,你做错了.