Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When I posted this question, I was missing a few important details. I want to elaborate on what was actually happening in case it will help someone in the future. My method under test was actually clearing the list that was being passed to the mock:</p> <pre><code>public class SomeDTO { } public class SomeRepository { public virtual void Write(IEnumerable&lt;SomeDTO&gt; list) { } } public class MainClass { private readonly SomeRepository _someRepository; private readonly List&lt;SomeDTO&gt; _testList = new List&lt;SomeDTO&gt;(); public MainClass(SomeRepository someRepository) { _someRepository = someRepository; } public void DoRepositoryWrite() { _testList.AddRange(Enumerable.Repeat(new SomeDTO(), 25)); _someRepository.Write(_testList); _testList.Clear(); } } class Program { static void Main(string[] args) { var mockSomeRepository = new Mock&lt;SomeRepository&gt;(); var mainClass = new MainClass(mockSomeRepository.Object); mainClass.DoRepositoryWrite(); mockSomeRepository.Verify(m =&gt; m.Write(It.IsAny&lt;IEnumerable&lt;SomeDTO&gt;&gt;()), Times.Once(), "Write was not called"); mockSomeRepository.Verify(m =&gt; m.Write(It.Is&lt;IEnumerable&lt;SomeDTO&gt;&gt;(l =&gt; l.Count() == 25)), Times.Once(), "Write was not called with a 25-element-list"); } } </code></pre> <p>Looking back it seems a little obvious, but the takeaway here for me is that the mock hangs on to a reference to the list it was passed. Therefore you need to be careful with any side effects that alter that list. </p> <p>To write the test properly, I needed to inspect the properties of the passed list immediately when the mocked method was called. To do this I used a callback:</p> <pre><code>int listCountAtTimeOfCall = 0; mockSomeRepository.Setup( m =&gt; m.Write(It.IsAny&lt;IEnumerable&lt;SomeDTO&gt;&gt;())).Callback &lt;IEnumerable&lt;SomeDTO&gt;&gt;(list =&gt; listCountAtTimeOfCall = list.Count()); ... do the work ... Assert.AreEqual(listCountAtTimeOfCall, 25); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload