2

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?

Community
  • 1
  • 1
epzee
  • 568
  • 8
  • 22
  • Can you expose a public virtual Property of this private readonly member? Plus, if the item in question is private, it sounds like you're not testing the right component. – Tejs Apr 17 '12 at 19:30
  • @Tejs you're right, please see the updated -now more accurate- question :) – epzee Apr 17 '12 at 19:55
  • Please don't edit a question that completely changes the meaning of it. Edits should be for clarifications, not fundamentally changing the meaning. If you want to ask a different question...ask a different question. – jason Apr 17 '12 at 20:57
  • @Jason ok, I'll revert the changes on this one and ask a new question – epzee Apr 17 '12 at 21:05
  • new question: http://stackoverflow.com/questions/10199544/how-to-mock-a-readonlycollectiont-property-using-moq – epzee Apr 17 '12 at 21:39

2 Answers2

6

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.

jason
  • 236,483
  • 35
  • 423
  • 525
  • This is basically everything I was going to say. You should only be testing the publicly visible interface anyways. – Tejs Apr 17 '12 at 19:38
  • @Tejs you're absolutely right. Please see the new question: http://stackoverflow.com/questions/10199544/how-to-mock-a-readonlycollectiont-property-using-moq – epzee Apr 17 '12 at 21:40
0

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;}
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179