[英]How to mock a private readonly IList<T> property using moq
I'm trying to mock this list: 我正在尝试模拟此列表:
private readonly IList<MyClass> myList = new List<MyClass>();
using this (as seen here ): 使用这个(如看到这里 ):
IList<MyClass> mockList = Builder<MyClass>.CreateListOfSize(5).Build();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(stakeHoldersList);
However at runtime I get an InvalidCastException: 但是在运行时,我收到一个InvalidCastException:
Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.
What am I doing wrong? 我究竟做错了什么?
Well, I think it's odd and frankly wrong to mock a private implementation detail. 好吧,我认为模拟一个私有的实现细节是很奇怪和坦率的错误。 Your tests shouldn't depend on private implementation details.
您的测试不应依赖于私有实现细节。
But the way that I'd do this if I were you is to add a constructor: 但是,如果您是我,我将执行此操作的方法是添加一个构造函数:
public Foo {
private readonly IList<MyClass> myList;
public Foo(IList<MyClass> myList) { this.myList = myList; }
}
and then use Moq to mock an instance of IList<MyClass>
and pass that through the constructor. 然后使用Moq模拟
IList<MyClass>
的实例,并将其通过构造函数传递。
If you don't like that suggestion, alternatively, make a virtual property: 如果您不喜欢该建议,请选择一个虚拟属性:
public Foo {
private readonly IList<MyClass> myList = new MyList();
public virtual IList<MyClass> MyList { get { return this.myList; } }
}
and then use Moq to override that property. 然后使用Moq覆盖该属性。
Still, you're doing it wrong. 不过,您做错了。
You have a field, but trying to setup a property get. 您有一个字段,但是尝试设置属性get。
Changing myList to property could work (not a moq expert here): 将myList更改为属性可以工作(这里不是最小起订量专家):
private readonly IList<MyClass> myListFiled = new List<MyClass>();
private IList<MyClass> myList {
get
{return myListFiled;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.