title: How to mock a ReadOnlyCollection<T> property using moq
body: <p>I'm trying to mock this ReadOnlyCollection property:</p>
  
  <pre><code>private readonly IList&lt;MyClass&gt; myList = new List&lt;MyClass&gt;();
  public virtual ReadOnlyCollection&lt;MyClass&gt; MyList
  {
     get
     {
         return new ReadOnlyCollectionBuilder&lt;MyClass&gt;(this.myList).ToReadOnlyCollection();
     }
  }
  </code></pre>
  
  <p>using this mock (as seen <a href="https://stackoverflow.com/questions/1454186/mocking-virtual-readonly-properties-with-moq">here</a>):</p>
  
  <pre><code>IList&lt;MyClass&gt; mockList = GetElements();
  mockObj.SetupGet&lt;IEnumerable&lt;MyClass&gt;&gt;(o =&gt; o.myList).Returns(mockList);
  </code></pre>
  
  <p>However at runtime I get an InvalidCastException:</p>
  
  <pre><code>Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
  type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.
  </code></pre>
  
  <p>What am I doing wrong?</p>