QuickStart
Introduction to Moq
Moq is intended to be simple to use, strong typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic.
Methods
var mock = new Mock<IFoo>();
mock.Expect(foo => foo.Execute("ping")).Returns(true);
// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Expect(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Expect(foo => foo.Submit(ref instance)).Returns(true);
// access invocation arguments
mock.Expect(x => x.Execute(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
// throwing when invoked
mock.Expect(foo => foo.Execute("reset")).Throws<InvalidOperationException>();
mock.Expect(foo => foo.Execute("")).Throws(new ArgumentException("command");
// lazy evaluating return value
mock.Expect(foo => foo.Count()).Returns(() => count);
// returning different values on each invocation
var mock = new Mock<IFoo>();
var calls = 0;
mock.Expect(foo => foo.Execute("ping"))
.Returns(() => calls)
.Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.Execute("ping"));
Matching Arguments
// any value
mock.Expect(foo => foo.Execute(It.IsAny<string>())).Returns(true);
// matching Func<int>, lazy evaluated
mock.Expect(foo => foo.Add(It.Is<int>(i => i % 2 == 0).Returns(true);
// matching ranges
mock.Expect(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive).Returns(true);
// matching regex
mock.Expect(x => x.Execute(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");
Properties
mock.Expect(foo => foo.Name).Returns("bar");
// auto-mocking hierarchies
mock.Expect(foo => foo.Bar.Baz.Name).Returns("baz");
mock.ExpectSet(foo => foo.Name, "foo" /* expected value */);
Events
// Raising an event on the mock
var handler = mock.CreateEventHandler<FooEventArgs>();
mock.FooEvent += handler;
handler.Raise(new FooEventArgs(fooValue));
// Causing an event to raise automatically
mock.Expect(foo => foo.Submit()).Raises(handler, EventArgs.Empty);
// The raised event would trigger behavior on the object under test, which
// you would make assertions about later (how its state changed as a consequence, typically)
Callbacks
var mock = new Mock<IFoo>();
mock.Expect(foo => foo.Execute("ping"))
.Returns(true)
.Callback(() => calls++);
// access invocation arguments
mock.Expect(foo => foo.Execute(It.IsAny<string>()))
.Returns(true)
.Callback((string s) => calls.Add(s));
// callbacks can be specified before and after invocation
mock.Expect(foo => foo.Execute("ping"))
.Callback(() => Console.WriteLine("Before returns"))
.Returns(true)
.Callback(() => Console.WriteLine("After returns"));
Verification
mock.Verify(foo => foo.Execute("ping"));
mock.VerifyGet(foo => foo.Name);
mock.VerifySet(foo => foo.Name, "foo");
Advanced Features
// get mock from a mocked instance
IFoo foo = // get instance somehow
var fooMock = Mock.Get(foo);
fooMock.Expect(f => f.Submit()).Returns(true);
// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now the IFoo also implements IDisposable :)
disposableFoo.Expect(df => df.Dispose());
// custom matchers
mock.Expect(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();
...
[Matcher]
public string IsLarge() { return null; }
public bool IsLarge(string arg)
{
return !String.IsNullOrEmpty(arg) && arg.Length > 100;
}
Read more
- TDD : Introduction to Moq
- Unit Testing Revisited - The evolution unit test with C-Sharp 3.0 (Google-translated)
- The automated testing continuum
- Unit Test Linq to Sql in ASP.Net MVC with Moq
- Introduction to Mocking with Moq (Video)
- Comparing Moq to Rhino Mocks
- Moq: Linq, Lambdas and Predicates applied to Mock Objects
- [http://www.goneeded.com/javas/articles/20080324/a1811942466.html
- Improved argument matchers in Moq
- Moq Triqs - Successive Expectations