2013-05-08 57 views
2

我对单元测试和ASP.NET MVC作为一个整体相对比较陌生,我正在尝试针对一个简单的控制器操作和存储库编写我的第一个单元测试(如下所示)使用Moq使用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); 

} 

回答

1

的井控制器你打电话:

var latestList = _submissionRepo.GetRecent(); 

你的模拟是设置为GetRecent(2)

修改您的模拟设置到:

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

编辑

而且你的断言应该是:

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

'result.Model'似乎完美地完成了这项工作!谢谢。 – 2013-05-13 22:31:23

2

此行

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

告诉MOQ返回集合时,它被称为与参数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); 
+0

我试图从参数删除到2的任何引用并且调用仍然显示为返回null而不是集合? – 2013-05-09 22:20:55

+0

您可能已经这样做了,但尝试使用It.IsAny ()作为匹配条件以查看是否正在调用GetRecent()。如果它被调用,那么它可能匹配GetRecent(10) - 默认参数。 – AlanT 2013-05-10 09:28:44

+0

@AlanT是的,我试过这个,但无济于事。这个问题真的让我难堪。 – 2013-05-13 07:52:36