Note that there are some explanatory texts on larger screens.

plurals
  1. POMocking a repository that has multiple calls to it with lambda expressions
    text
    copied!<p>I'm testing a recursive function that's used to build a tree based on data in the database. For the purposes of this question, just assume that the entity has it's own entity id and then the id of its parent.</p> <p>During each call of the recursive function, this gets run against the repository:</p> <pre><code> List&lt;MyEntity&gt; children = dsService.GetMany&lt;MyEntity&gt;(x =&gt; x.ParentId == currentId) </code></pre> <p>Normally, I'd just mock the repository and set something like this:</p> <pre><code>dsService.GetMany&lt;MyEntity&gt;(x =&gt; x.ParentId == 1).Returns(new List&lt;MyEntity&gt; { }); dsService.GetMany&lt;MyEntity&gt;(x =&gt; x.ParentId == 2).Returns(new List&lt;MyEntity&gt; { myentity, myotherentity}); </code></pre> <p>However, NSubstitute (and based on quick googling, other mocking frameworks but I'll admit I wasn't super thorough) have issues with LINQ queries and I can't use that for determining what to return unless the queries are the exact same (same variable names, same order, etc.). I've also seen that I can set the first function call to GetMany (regardless of parameters) to return one thing, the second to return another, etc.</p> <p>I don't really like either of those approaches since with the first, that assumes that the function calls/tree traversal will always been in the exact same order (and actually as I'm reading this, since it's in a loop, it would be using currentId as the variable name every time so that wouldn't work since there'd be no way to differentiate between calls) and the second one assumes the order of variables, the names of the variables, etc. will stay the exact same. Refactoring can/will break the unit test in these cases.</p> <p>So what's the best approach here? Are there any mocking frameworks that can handle lambdas like this? Is my best approach to create a fake repository with a list in it for the unit test to query against and return the relevant result? Something else entirely?</p>
 

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