How to Change Default Return Values in MOQ

In Moq, any mocked method or property without defined behavior will return the default value of its return type. This means that for all reference types a null value is returned. It turns out that this behavior is easily configurable by calling the SetReturnsDefault() of T method, and passing in a default value of your choosing.

In the example bellow I've specified that I want all methods or properties that return objects of type string to return the fixed string “John Smith” instead of the default null value.

public class CustomerHelper { private ICustomerService customerService; public CustomerHelper(ICustomerService customerService) { this.customerService = customerService; } public string PrintGreeting(int customerId) { return string.Format("Dear {0}", customerService.GetCustomerName(customerId)); } } [TestMethod] public void Will_Print_Customer_Greeting() { var customerServiceMock = new Mock<ICustomerService>(); customerServiceMock.SetReturnsDefault("John Smith"); CustomerHelper customerHelper = new CustomerHelper(customerServiceMock.Object); var greeting = customerHelper.PrintGreeting(1); Assert.AreEqual("Dear John Smith", greeting); }

SetReturnsDefault() can be used as an alternative to Setups, but one obvious limitation is that all strings, throughout the entire mock, will now be returned as “John Smith”. If you need more granular control at the method or property level I recommend using Setups instead.