使用Moq通过存储库返回集合

时间:2013-05-08 23:42:02

标签: asp.net-mvc nunit moq

我对单元测试和ASP.NET MVC作为一个整体相对较新,我正在尝试使用Moq针对简单的控制器操作和存储库(如下所示)编写我的第一个单元测试。

ISubmissionRepository.cs

public interface ISubmissionRepository
{
    IList<Submission> GetRecent(int limit = 10);
}

HomeController.cs:

/* Injected using Unit DIC */
public HomeController(ISubmissionRepository submissionRepository)
{
    _submissionRepo = submissionRepository;
}

public ActionResult Index()
{

    var latestList = _submissionRepo.GetRecent();
    var viewModel = new IndexViewModel {
        NumberOfSubmissions = latestList.Count(),
        LatestSubmissions = latestList
    };
    return View(viewModel);
}

下面是我正在编写的单元测试,但是我的模拟存储库调用似乎没有返回任何内容,我不知道为什么。我是否正确地模拟了我的存储库调用?

HomeControllerTest.cs

[Test]
public void Index()
{
    IList<Submission> submissions = new List<Submission>
    {
        new Submission {Credit = "John Doe", Description = "Hello world", ID = 1, Title = "Example Post"},
        new Submission {Credit = "John Doe", Description = "Hello world", ID = 2, Title = "Example Post"}
    };

    Mock<ISubmissionRepository> mockRepo = new Mock<ISubmissionRepository>();
    mockRepo.Setup(x => x.GetRecent(2)).Returns(submissions);

    /* 
    * This appears to return null when a breakpoint is set
    var obj = mockRepo.Object;
    IList<Submission> temp = obj.GetRecent(2);
    */

    controller = new HomeController(mockRepo.Object);
    ViewResult result = controller.Index() as ViewResult;

    Assert.NotNull(result);
    Assert.IsInstanceOf<IndexViewModel>(result);

}

2 个答案:

答案 0 :(得分:2)

这一行

 mockRepo.Setup(x => x.GetRecent(2)).Returns(submissions);

告诉moq在使用param 2调用它时返回该集合。您的控制器将其称为

var latestList = _submissionRepo.GetRecent();

这些是在Moq中单​​独设置的,因此不会返回结果。您可以删除测试中的2或让控制器用2调用它来获得返回。

编辑 - 更新答案

尝试将模拟设置为:

mockRepo.Setup(x => x.GetRecent(It.Is<int>(i => i == 2))).Returns(submissions);

它告诉它只有在参数列表中看到2才返回。你的控制器也需要用2调用它才能恢复工作。

否则,将其设置为与参数

无关
mockRepo.Setup(x => x.GetRecent(It.IsAny<int>())).Returns(submissions);

答案 1 :(得分:1)

你正在打电话给你的控制器:

var latestList = _submissionRepo.GetRecent();

您的模拟已设置为GetRecent(2)

将模拟设置修改为:

mockRepo.Setup(x => x.GetRecent()).Returns(submissions);

修改

你的断言也应该是:

Assert.IsInstanceOf<IndexViewModel>(result.Model);