SteGriff

Blog

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

blankLogoService
	.Setup(r => r.GetLogoForOrganisation(It.IsAny<int>()))
	.Returns("");

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

Notes

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

varyLogoService
	.Setup(r => r.GetLogoForOrganisation(It.Is<int>(x => x == 101)))
	.Returns("fabrikam_rgb_512.png");
	
varyLogoService
	.Setup(r => r.GetLogoForOrganisation(It.Is<int>(x => x == 102)))
	.Returns("contoso-small.png");
	
var myThingUnderTest = new ThingUnderTest(varyLogoService.Object);

// Act and Assert ...

Notes

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