Moq:如何根据方法参数返回结果?

时间:2011-10-26 01:34:00

标签: moq

ICustomerRepository定义: Customer GetCustomerByID(int CustomerID);

//Arrange
var customers = new Customer()
{
   new Customer() { CustomerID = 1, Name = "Richard" },
   new Customer() { CustomerID = 2, Name = "Evan" },
   new Customer() { CustomerID = 3, Name = "Marie-France" },
}.AsQueryable(); 

Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();

我如何告诉Moq根据CustomerID参数???

返回正确的客户

我已经能够设置第一部分,但不能设置返回对象。

 mock.Setup(m => m.GetCustomerByID(It.Is<int>(i => i >= 0))).Returns(/// To be define///)

这个想法会得到与此相同的结果:

public Customer GetCustomerByID(int CustomerID)
{
  return customers.FirstOrDefault(c => c.CustomerID == CustomerID);
}

感谢您的帮助

1 个答案:

答案 0 :(得分:6)

mock.Setup(x => x.GetCustomerByID(It.IsAny<int>()))
    .Returns((int id) => 
    customers.FirstOrDefault(c => c.CustomerID == id));

只需让客户List<Customer> - 不需要AsQueryable。