How do I mock DbContext using NSubstitute and then add/remove data
<p>I need to mock EF's <code>DbContext</code>. I use <a href="https://stackoverflow.com/a/21075569/3959480">the approach here</a> and it works well.</p>

<pre><code>// mock a DbSet
var mockDbSet = Substitute.For&lt;DbSet&lt;Foo&gt;, IQueryable&lt;Foo&gt;&gt;();
var data = new List&lt;Foo&gt;().AsQueryable();
((IQueryable&lt;Foo&gt;)mockDbSet).Provider.Returns(data.Provider);
((IQueryable&lt;Foo&gt;)mockDbSet).Expression.Returns(data.Expression);
((IQueryable&lt;Foo&gt;)mockDbSet).ElementType.Returns(data.ElementType);
((IQueryable&lt;Foo&gt;)mockDbSet).GetEnumerator().Returns(data.GetEnumerator());
// now add it to a mock DbContext
var mockContext = Substitute.For&lt;MyDbContextClass&gt;();
mockContext.Set&lt;Foo&gt;().Returns(mockDbSet);
</code></pre>

<p>However in some tests I need to be able to call <code>mockContext.Set&lt;Foo&gt;().Add(someFoo)</code> and <code>mockContext.Set&lt;Foo&gt;().Remove(otherFoo)</code>, and for the underlying add/remove logic to work.</p>

<p>I tried this:</p>

<pre><code>mockDbSet.When(x =&gt; x.Add(Arg.Any&lt;Foo&gt;())).Do(x =&gt; data.Add(x.Arg&lt;Foo&gt;()));
</code></pre>

<p>but it throws with <code>Collection was modified; enumeration operation may not execute.</code></p>

<p><em>So how do I implement add/remove functionality?</em></p>