我对 Moq 完全陌生,到目前为止,我只是按照 Pro asp.net 框架中概述的示例进行操作。在书中,一些杂乱无章的东西放在了 Controller 中,例如通过 id 获取客户——可能是为了简洁。我决定将这种类型的功能放在存储库中,然后像这样在 Controller 中调用它“customerRepository.GetCustomerByID(id);”测试这样的东西的最佳方法是什么?我创建了以下单元测试,由于某种原因它返回一个空客户。
List<Customer> customer = new List<Customer>();
customer.Add(new Customer { CustomerId = 1, FirstName = "test", LastName = "wods", Sex = true });
mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.Customers).Returns(customer.AsQueryable());
CustomersController controller = new CustomersController(mockRepos.Object);
//Act
ViewResult results = controller.Edit(1);
var custRendered = (Customer)results.ViewData.Model;
Assert.AreEqual(2, custRendered.CustomerId);
Assert.AreEqual("test", custRendered.FirstName);
和 Controller
public ViewResult Edit(int id)
{
Customer customer = customerRepository.GetCustomerByID(id);
return View(customer); //this just returns null??
}
我想我很傻,但任何帮助都将不胜感激。
最佳答案
您需要设置您的模型以期待调用 GetCustomerById
而不是 Customers
属性(property)。像这样的东西:
mockRepos.Setup(x => x.GetCustomerById(1)).Returns(customer[0]);
关于asp.net-mvc - 带 Moq 的单元测试存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305340/