Show Menu

Moq Cheat Sheet by

development     programming     moq     tests

Stub - Just a replac­ement

// Create a stub
var mock = new Mock<IMyDependency>();

// Get the Stub
var myDep = mock.Object;

Assert.That(myDep .GetValue(), Is.EqualTo(0));
By default: Methods with returning types return default values. (e.g. int GetVal­ue() returns 0;

Spy - What happened?

// Create a spy
var mock = new Mock<IMyDependency>();

// Spy on executions
mock.Verify(myDep => myDep.GetValue());
Optional:
Verify can be called with optional argument that asserts how many times the method as called: AtLeas­tOnce, AtLeast, AtMost, AtMost­Once, Betwee­nEx­clu­sive, Betwee­nIn­clu­sive, Exactly, Once, Never

Tip: Always strive to use concrete expect­ations. Avoid AtMost, AtLeast and Between.

Spy via Callbacks

// Create a spy
var mock = new Mock<IMyDependency>();

string usedArg;
mock
    // Setup to capture any call to done to DoSomething method.
    .Setup(myDep => myDep.DoSomething(It.IsAny<String>())
    // Callback function is called when DoSomething was called.
    .Callback<String>(arg => usedArg = arg);

// Executing with "test" argument
mock.Object.DoSomething("test");

Assert.That(usedArg, Is.EqualTo("test"));
 

Mock - Do what I say!

// Create a mock
var mock = new Mock<IMyDependency>();

mock
    // What behavior is going to be mocked
    .Setup(myDep => myDep.GetValue())
    // What's going to be returned by GetValue()
    .Returns(1);

// Using the object
var myDep = mock.Object;

Assert.That(myDep .GetValue(), Is.EqualTo(1));

Mock - Setup - Matching Arguments

Expected Argument
Setup
1
Setup(e => e.Get(1))
Any
Setup(e => e.Get(­It.I­sA­ny<­int­>())
> 10
Setup(e => e.Get(­It.I­s<­int­>(i => i > 10))
Range [0..10]
Setup(e => e.Get(­It.I­sI­nRa­nge­<in­t>(0, 10, Range.I­nc­lus­ive))
An instance of a mock can have more than 1 setup for a given method provided we setup the method with different arguments.

Tip: Avoid using non specific values on capture, except when it's possible to validate what was provided.

Mock - Setup - Returns

value
Setup­(...).R­et­urn­s(v­alue)
access argument
Setup­(...).R­et­urn­s(arg => arg + 10)
Throw exception
Setup­(...).T­hr­ows­<Ex­cep­tio­n>()
Throw exception with message
Setup­(...).T­hr­ows(new Except­ion­("My Messag­e"))
Lazy access
Setup­(...).R­et­urns(() => value)

Download the Moq Cheat Sheet

1 Page
//media.cheatography.com/storage/thumb/alienengineer_moq.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet

          More Cheat Sheets by AlienEngineer