Note that there are some explanatory texts on larger screens.

plurals
  1. POMoq an IQueryable that returns itself
    text
    copied!<p>I'm setting up a test using a mocked <code>IQueryable</code> (using Moq) that I want to return itself when <code>.Where()</code> is called on it:</p> <pre><code>[SetUp] public void Setup() { mockPocos = new Mock&lt;IQueryable&lt;Poco&gt;&gt;(); mockPocos.Setup(foo =&gt; foo.Where(It.IsAny&lt;Expression&lt;Func&lt;Poco, bool&gt;&gt;&gt;())) .Returns(mockPocos.Object); } </code></pre> <p>(This way, I can mock methods/properties like <code>.Count</code> and know that regardless of how many times the method being tested runs queries over the <code>IQueryable</code>, it will return values I can control.)</p> <p>This compiles, but when I run it, I get this exception:</p> <pre><code>Tests.PocoTest.TestPocoQueryable: SetUp : System.NotSupportedException : Expression references a method that does not belong to the mocked object: foo =&gt; foo.Where&lt;Poco&gt;(It.IsAny&lt;Expression`1&gt;()) </code></pre> <p>How can I get this to work?</p> <hr> <p>EDIT: In response to the comments, this is why I want to use Moq like this.</p> <p>In the method I'm testing, I have code like this:</p> <pre><code>public int[] MethodToTest(IQueryable&lt;Poco&gt; pocos, MockableDependency dependency) { var mostRecentUpdate = (from poco in pocos select poco.Date_Last_Updated).Max(); var recentPocos = pocos.Where(x =&gt; x.Date_Last_Updated.CompareTo(mostRecentUpdate) &gt;= 0); ///...snip... result[0] = SomePrivateCalculation(recentPocos.Count); result[1] = dependency.DoADifferentCalculation(recentPocos); } </code></pre> <p>I'm already mocking the <code>MockableDependency</code>, so I don't actually need to worry about what <code>Poco</code>s are in <code>pocos</code>. However, I would like to be able to control what the value of <code>recentPocos.Count</code> is, and I would like to be able to know that it will return the same value no matter how many queries are run over <code>pocos</code> before <code>.Count</code> is accessed.</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