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
- We set up one Method call at a time
- We describe what it can accept (for my purposes, the passed-in
int
can be anything) - The mock always returns the same thing here: an empty string.
IsAny
is a method call, so it needs the method call parenthesesIt.IsAny<int>()
… don’t miss em!- Remember
.Object
(it’s areadonly property
)
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
- We change
It.IsAny<int>
toIt.Is<int>( lambda )
- The lambda function decides whether to match the parameter, it accepts a parameter of type
T
from theIs<T>
generic and returns true/false.
That’s all I’m doing on this for now :)