// Create a stub
var mock = new Mock<IMyDependency>();
// Get the Stub
var myDep = mock.Object;
Assert.That(myDep .GetValue(), Is.EqualTo(0));
int GetValue() returns 0;
// Create a spy
var mock = new Mock<IMyDependency>();
// Spy on executions
mock.Verify(myDep => myDep.GetValue());
Verify can be called with optional argument that asserts how many times the method as called: AtLeastOnce, AtLeast, AtMost, AtMostOnce, BetweenExclusive, BetweenInclusive, Exactly, Once, Never// 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);{{nl}}
// Executing with "test" argument
mock.Object.DoSomething("test");{{nl}}
Assert.That(usedArg, Is.EqualTo("test"));
// Create a mock
var mock = new Mock<IMyDependency>();{{nl}}
mock
// What behavior is going to be mocked
.Setup(myDep => myDep.GetValue())
// What's going to be returned by GetValue()
.Returns(1);{{nl}}
// Using the object
var myDep = mock.Object;{{nl}}
Assert.That(myDep .GetValue(), Is.EqualTo(1));
|
Expected Argument
|
Setup
|
|
1
|
Setup(e => e.Get(1)) |
|
Any
|
Setup(e => e.Get(It.IsAny<int>()) |
|
> 10
|
Setup(e => e.Get(It.Is<int>(i => i > 10)) |
|
Range [0..10]
|
Setup(e => e.Get(It.IsInRange<int>(0, 10, Range.Inclusive)) |
|
value
|
Setup(...).Returns(value) |
|
access argument
|
Setup(...).Returns(arg => arg + 10) |
|
Throw exception
|
Setup(...).Throws<Exception>() |
|
Throw exception with message
|
Setup(...).Throws(new Exception("My Message")) |
|
Lazy access
|
Setup(...).Returns(() => value) |
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.