私は単体テストと 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);
}