Show Menu
Cheatography

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 GetValue()
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­etu­rns­(value)
access argument
Setup(...).R­etu­rns(arg => arg + 10)
Throw exception
Setup(...).T­hro­ws<­Exc­ept­ion­>()
Throw exception with message
Setup(...).T­hro­ws(new Except­ion­("My Messag­e"))
Lazy access
Setup(...).R­etu­rns(() => value)
           
 

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
          Python Cheat Sheet

          More Cheat Sheets by AlienEngineer