C# – Using MOQ to test controller

asp.net-mvcc++moqunit-testing

I'm having trouble writing a unit test for one of my controller actions. Here's the details.

This view is strongly typed:

Inherits="System.Web.Mvc.ViewPage<IEnumerable<Request>>"

Here is the method in the controller under test:

    // GET: /Request/List
    public ActionResult List()
    {
        return View("List", 
            requestRepository.GetAll(User.Id).OrderByDescending(x => x.Id));
    }

Here is the excerpt from the test (nUnit, MOQ) that is giving me problems:

    //mockRequestRepository
    //    .Setup(repo => repo.GetAll(It.IsAny<int>()))
    //    .Returns(List<Request>());
    //mockRequestRepository
    //    .Setup(repo => repo.GetAll(It.IsAny<int>()))
    //    .Returns(IList<Request>());
    //mockRequestRepository
    //    .Setup(repo => repo.GetAll(It.IsAny<int>()))
    //    .Returns(IEnumerable<List<Request>>());
    mockRequestRepository
          .Setup(repo => repo.GetAll(It.IsAny<int>()))
          .Returns(It.IsAny<List<Request>>());

The first three setup statements will not compile because of an ambiguous invocation:

Moq.Language.Flow.IReturnsResult<Core.Repositories.IRequestRepository>
Returns(System.Collections.Generic.IList<Core.Entities.Request> 
(in interface IReturns<IRequestRepository, IList<Request>>)

Moq.Language.Flow.IReturnsResult<Core.Repositories.IRequestRepository>
Returns(System.Func<System.Collections.Generic.IList<Core.Entities.Request>> 
(in interface IReturns<IRequestRepository, IList<Request>>)

The fourth will compile but throws this error when it reaches the return statement in the controller action:

InnerException  {"Value cannot be null.\r\nParameter name: source"} 
System.Exception {System.ArgumentNullException}

I don't think it is relevant, but there are two overloads on the method, GetAll() and GetAll(int UserId). I'm sure it has something to do the the OrderBy on the List, but I'm pretty shaky on the Func concepts. Thanks for your help!

Best Solution

Try this:

mockRequestRepository.Setup(repo => repo.GetAll(It.IsAny<int>()))
    .Returns(new List<Request> { /* empty list */ });

or

mockRequestRepository.Setup(repo => repo.GetAll(It.IsAny<int>()))
    .Returns(new List<Request> {
        new Request { Prop1 = ..., PropN = ... },
        new Request { Prop1 = ..., PropN = ... },
        ...
    });