Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Define Different Return Values in MOQ

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Wed May 27 2015

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); }

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter