Using MOQ to test the controller

I am having trouble writing a unit test for one of my controller actions. Here are the details.

This view is strongly typed:

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

The following is a test method for the controller:

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

Here is an excerpt from the test (nUnit, MOQ) that is causing 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 installation instructions will not be compiled due to the ambiguous call:

 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 do not think this is relevant, but there are two method overloads: GetAll () and GetAll (int UserId). I'm sure he has something to do OrderBy on the List, but I'm pretty shaky in Func concepts. Thank you for your help!

+4
source share
2 answers

Try the following:

 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 = ... }, ... }); 
+5
source

You can also use NBuilder with moq.

 _repository.Setup(rep => rep.GetAll(It.IsAny<int>())) // <-- Moq magic .Returns( Builder<Request>.CreateListOfSize(10).Build() // <-- NBuilder magic ); 
+8
source

Source: https://habr.com/ru/post/1286203/


All Articles