代码之家  ›  专栏  ›  技术社区  ›  Les

使用MOQ测试控制器

  •  5
  • Les  · 技术社区  · 17 年前

    我在为我的一个控制器操作编写单元测试时遇到问题。这是详细情况。

    此视图是强类型:

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

    下面是被测控制器中的方法:

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

    以下是给我带来问题的测试(nunit,moq)的摘录:

        //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>>());
    

    由于调用不明确,前三条SETUP语句将无法编译:

    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>>)
    

    第四个将编译,但在控制器操作中到达RETURN语句时抛出此错误:

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

    我不认为它是相关的,但是方法有两个重载,getall()和getall(int userid)。我肯定它和列表中的orderby有关系,但我对func概念相当不确定。谢谢你的帮助!

    2 回复  |  直到 16 年前
        1
  •  6
  •   eu-ge-ne    17 年前

    试试这个:

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

    mockRequestRepository.Setup(repo => repo.GetAll(It.IsAny<int>()))
        .Returns(new List<Request> {
            new Request { Prop1 = ..., PropN = ... },
            new Request { Prop1 = ..., PropN = ... },
            ...
        });
    
        2
  •  8
  •   Pure.Krome    16 年前

    您也可以使用 NBuilder 与MoQ一起。

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