Define Different Return Values in MOQ

Sometimes it can be useful to simulate different return values when mocking methods that are called multiple times in the code under test. It turns out that this becomes trivial if you're using MOQ to do your mocking.

In addition to Standard Setups, MOQ offers a SetupSequence that lets you define behavior for an arbitrary number of calls to a method.

The following code listing shows how to test a simple method with two calls to the same GetCustomer() method:

The key point to notice is the chained "Return" call defined on the mocked object.

public class CustomerHelper { ICustomerService customerService; public CustomerHelper(ICustomerService customerService) { this.customerService = customerService; } public string GetListOfCustomers(int[] ids) { StringBuilder sb = new StringBuilder(); foreach(int id in ids) { sb.AppendLine(customerService.GetCustomer(id)); } return sb.ToString(); } } [TestMethod] public void Will_Return_List_Of_Customers_With_LineBreaks() { var service = new Mock(); service.SetupSequence(s => s.GetCustomer(It.IsAny<int>())).Returns("Joe").Returns("Jane"); CustomerHelper helper = new CustomerHelper(service.Object); var customers = helper.GetListOfCustomers(new[] { 1, 2 }); Assert.AreEqual("Joe\r\nJane\r\n", customers); }