Next & Previous

How to use Moq

This is more of a ‘Note to Self’ article… something else I forget a lot… :)

First, install the Moq Nuget package.

Example which always returns the same value

Let’s use the Mock class. You can only mock an interface, never a concrete type.

// Get a LogoService which always provides empty ""
var blankLogoService = new Mock<ILogoService>();

	.Setup(r => r.GetLogoForOrganisation(It.IsAny<int>()))

When you come to use your Mock instance, you have to call upon blankLogoService.Object to make Moq conrete-ify the class:

var myThingUnderTest = new ThingUnderTest(blankLogoService.Object);


Example which varies return value based on arguments

Here’s a mock object which differs its output based on the passed-in value:

// Get a LogoService which gives test data for two different Organisations
// 101 -> Fabrikam ("fabrikam_rgb_512.png")
// 102 -> Contoso ("contoso-small.png")
var varyLogoService = new Mock<ILogoService>();

	.Setup(r => r.GetLogoForOrganisation(It.Is<int>(x => x == 101)))
	.Setup(r => r.GetLogoForOrganisation(It.Is<int>(x => x == 102)))
var myThingUnderTest = new ThingUnderTest(varyLogoService.Object);

// Act and Assert ...


That’s all I’m doing on this for now :)