Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

moq

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

like image 387
Richard77 Avatar asked Feb 22 '23 14:02

Richard77


1 Answers

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.

like image 197
TrueWill Avatar answered May 08 '23 06:05

TrueWill