Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MOQ to test controller

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!

like image 249
Les Avatar asked Jun 14 '09 20:06

Les


2 Answers

You can also use NBuilder together with moq.

_repository.Setup(rep => rep.GetAll(It.IsAny<int>()))  // <-- Moq magic
    .Returns( 
        Builder<Request>.CreateListOfSize(10).Build()  // <-- NBuilder magic
    );
like image 134
matma Avatar answered Oct 08 '22 03:10

matma


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 = ... },
        ...
    });
like image 26
eu-ge-ne Avatar answered Oct 08 '22 02:10

eu-ge-ne