views:

651

answers:

2

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!

+3  A: 

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 = ... },
        ...
    });
eu-ge-ne
Thanks! This makes perfect sense as soon as I see it. Doh!
Leslie
+4  A: 

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
    );
matma
Interesting. I'll have a look. Thanks.
Leslie
+1, didn't know about NBuilder
BengtBe
+1 I love this combination! No longer to I have to bother building my own test objects!
MPritch
+! for NBuilder also :) WOW!
Pure.Krome