How to mock a private readonly IList<T> property using moq

那年仲夏 提交于 2019-12-13 15:35:06

问题


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:

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?


回答1:


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.

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.

Still, you're doing it wrong.




回答2:


You have a field, but trying to setup a property get.

Changing myList to property could work (not a moq expert here):

private readonly IList<MyClass> myListFiled = new List<MyClass>();
private IList<MyClass> myList {
  get 
   {return myListFiled;}
}


来源:https://stackoverflow.com/questions/10197819/how-to-mock-a-private-readonly-ilistt-property-using-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!