gpt4 book ai didi

asp.net-mvc - 使用 Moq 通过存储库返回集合

转载 作者:行者123 更新时间:2023-12-04 04:58:25 26 4
gpt4 key购买 nike

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

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

}

最佳答案

那么在您的 Controller 中,您正在调用:

var latestList = _submissionRepo.GetRecent();

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

将您的模拟设置修改为:
mockRepo.Setup(x => x.GetRecent()).Returns(submissions);

编辑

你的断言也应该是:
Assert.IsInstanceOf<IndexViewModel>(result.Model);

关于asp.net-mvc - 使用 Moq 通过存储库返回集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com