Richard77
Richard77

Reputation: 21631

Moq: How to return result depending on the method parameter?

ICustomerRepository define: 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>();

How do I tell Moq to return the correct customer depending on the CustomerID paremeter???

I've been able to set up the first part, but not the return object.

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

The Idea is to have the same result as this:

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

Thanks for helping

Upvotes: 6

Views: 2580

Answers (1)

TrueWill
TrueWill

Reputation: 25523

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

Just make customers a List<Customer> - no need for AsQueryable.

Upvotes: 12

Related Questions