Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I mock IQueryable<T>
    primarykey
    data
    text
    <p>I am creating a repository that exposes IQueryable. What is the best way to mock this out for my unit testing?</p> <p>Since I am using RhinoMocks for the rest of my mock objects, I tried to do the following:</p> <pre><code>IQueryable&lt;MyObject&gt; QueryObject = MockRepository.GenerateStub&lt;IQueryable&lt;MyObject&gt;&gt;(); </code></pre> <p>This doesn't work though so I tried doing this:</p> <pre><code>IQueryable&lt;MyObject&gt; QueryObject = (new List&lt;MyObject&gt; { new MyObject() }).AsQueryable(); </code></pre> <p>Is there a better way to do this, or have any other mocking frameworks built support for IQueryable in?</p> <p>My repository interface looks like this:</p> <pre><code>public interface IRepository&lt;T&gt; where T : TableServiceEntity { IQueryable&lt;T&gt; Table { get; } void Attach(T existingItem); void Delete(T itemToDelete); void Insert(T newItem); T Load(string partitionKey, string rowKey); IEnumerable&lt;T&gt; Load(string partitionKey); IEnumerable&lt;T&gt; Query(IQueryable&lt;T&gt; query); IEnumerable&lt;T&gt; Last(int count); T Last(); void Update(T item); } </code></pre> <p>Here is the method that I want to test:</p> <pre><code>public Post LoadPost(int year, int month, int day, string slug) { var query = from p in _blogRepository.Table where p.PartitionKey == Key.Partition(year, month, day) &amp;&amp; p.Slug == slug select p; var posts = _blogRepository.Query(query.Take(1)); return posts.First(); } </code></pre> <p>Then here is the test as I have it right now that will test LoadPost.</p> <pre><code>[Fact] public void LoadWillRetrieveByPartitionKeyAndRowKeyWhenUsingUriFormat() { Repository .Stub(x =&gt; x.Query(Arg&lt;IQueryable&lt;Post&gt;&gt;.Is.Anything)) .Return(new List&lt;Post&gt; {_post}); var result = Service.LoadPost( _post.Year(), _post.Month(), _post.Day(), _post.Slug); Assert.NotNull(result); } </code></pre> <p>The code is taken from my <a href="http://azureblog.codeplex.com">AzureBlog</a> project.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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