我对单元测试和整个 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);
}