Quickstart (original) (raw)

Moq is intended to be simple to use, strongly typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).

Outline

Methods

Definitions for the following examples:

using Moq;

// Assumptions:

public interface IFoo { Bar Bar { get; set; } string Name { get; set; } int Value { get; set; } bool DoSomething(string value); bool DoSomething(int number, string value); Task DoSomethingAsync(); string DoSomethingStringy(string value); bool TryParse(string value, out string outputValue); bool Submit(ref Bar bar); int GetCount(); bool Add(int value); }

public class Bar { public virtual Baz Baz { get; set; } public virtual bool Submit() { return false; } }

public class Baz { public virtual string Name { get; set; } }

You can setup the behavior of any of a mock's overridable methods using Setup, combined with e.g. Returns (so they return a value) or Throws (so they throw an exception):

var mock = new Mock(); mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

// out arguments var outString = "ack"; // TryParse will return true, and the out argument will return "ack", lazy evaluated mock.Setup(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.Setup(foo => foo.Submit(ref instance)).Returns(true);

// access invocation arguments when returning a value mock.Setup(x => x.DoSomethingStringy(It.IsAny())) .Returns((string s) => s.ToLower()); // Multiple parameters overloads available

// throwing when invoked with specific parameters mock.Setup(foo => foo.DoSomething("reset")).Throws(); mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command"));

// lazy evaluating return value var count = 1; mock.Setup(foo => foo.GetCount()).Returns(() => count);

// async methods (see below for more about async): mock.Setup(foo => foo.DoSomethingAsync().Result).Returns(true);

Async Methods

There are several ways to set up "async" methods (e.g. methods returning a Task<T> or ValueTask<T>):

Matching Arguments

// any value mock.Setup(foo => foo.DoSomething(It.IsAny())).Returns(true);

// any value passed in a ref parameter (requires Moq 4.8 or later): mock.Setup(foo => foo.Submit(ref It.Ref.IsAny)).Returns(true);

// matching Func, lazy evaluated mock.Setup(foo => foo.Add(It.Is(i => i % 2 == 0))).Returns(true);

// matching ranges mock.Setup(foo => foo.Add(It.IsInRange(0, 10, Range.Inclusive))).Returns(true);

// matching regex mock.Setup(x => x.DoSomethingStringy(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

Properties

mock.Setup(foo => foo.Name).Returns("bar");

// auto-mocking hierarchies (a.k.a. recursive mocks) mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz");

// expects an invocation to set the value to "foo" mock.SetupSet(foo => foo.Name = "foo");

// or verify the setter directly mock.VerifySet(foo => foo.Name = "foo");

// start "tracking" sets/gets to this property mock.SetupProperty(f => f.Name);

// alternatively, provide a default value for the stubbed property mock.SetupProperty(f => f.Name, "foo");

// Now you can do:

IFoo foo = mock.Object; // Initial value was stored Assert.Equal("foo", foo.Name);

// New value set which changes the initial value foo.Name = "bar"; Assert.Equal("bar", foo.Name);

mock.SetupAllProperties();

Events

// Setting up an event's add and remove accessors (requires Moq 4.13 or later): mock.SetupAdd(m => m.FooEvent += It.IsAny())...; mock.SetupRemove(m => m.FooEvent -= It.IsAny())...;

// Raising an event on the mock mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));

// Raising an event on the mock that has sender in handler parameters mock.Raise(m => m.FooEvent += null, this, new FooEventArgs(fooValue));

// Raising an event on a descendant down the hierarchy mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));

// Causing an event to raise automatically when Submit is invoked mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, 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)

// Raising a custom event which does not adhere to the EventHandler pattern public delegate void MyEventHandler(int i, bool b); public interface IFoo { event MyEventHandler MyEvent; }

var mock = new Mock(); ... // Raise passing the custom arguments expected by the event delegate mock.Raise(foo => foo.MyEvent += null, 25, true);

Callbacks

var mock = new Mock(); var calls = 0; var callArgs = new List();

mock.Setup(foo => foo.DoSomething("ping")) .Callback(() => calls++) .Returns(true);

// access invocation arguments mock.Setup(foo => foo.DoSomething(It.IsAny())) .Callback((string s) => callArgs.Add(s)) .Returns(true);

// alternate equivalent generic method syntax mock.Setup(foo => foo.DoSomething(It.IsAny())) .Callback(s => callArgs.Add(s)) .Returns(true);

// access arguments for methods with multiple parameters mock.Setup(foo => foo.DoSomething(It.IsAny(), It.IsAny())) .Callback<int, string>((i, s) => callArgs.Add(s)) .Returns(true);

// callbacks can be specified before and after invocation mock.Setup(foo => foo.DoSomething("ping")) .Callback(() => Console.WriteLine("Before returns")) .Returns(true) .Callback(() => Console.WriteLine("After returns"));

// callbacks for methods with ref / out parameters are possible but require some work (and Moq 4.8 or later): delegate void SubmitCallback(ref Bar bar);

mock.Setup(foo => foo.Submit(ref It.Ref.IsAny)) .Callback(new SubmitCallback((ref Bar bar) => Console.WriteLine("Submitting a Bar!")));

// returning different values on each invocation var mock = new Mock(); var calls = 0; mock.Setup(foo => foo.GetCount()) .Callback(() => calls++) .Returns(() => calls); // returns 0 on first invocation, 1 on the next, and so on Console.WriteLine(mock.Object.GetCount());

// access invocation arguments and set to mock setup property mock.SetupProperty(foo=>foo.Bar); mock.Setup(foo => foo.DoSomething(It.IsAny())) .Callback((string s) => mock.Object.Bar=s) .Returns(true);

Verification

mock.Verify(foo => foo.DoSomething("ping"));

// Verify with custom error message for failure mock.Verify(foo => foo.DoSomething("ping"), "When doing operation X, the service should be pinged always");

// Method should never be called mock.Verify(foo => foo.DoSomething("ping"), Times.Never());

// Called at least once mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce());

// Verify getter invocation, regardless of value. mock.VerifyGet(foo => foo.Name);

// Verify setter invocation, regardless of value. mock.VerifySet(foo => foo.Name);

// Verify setter called with specific value mock.VerifySet(foo => foo.Name ="foo");

// Verify setter with an argument matcher mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive));

// Verify event accessors (requires Moq 4.13 or later): mock.VerifyAdd(foo => foo.FooEvent += It.IsAny()); mock.VerifyRemove(foo => foo.FooEvent -= It.IsAny());

// Verify that no other invocations were made other than those already verified (requires Moq 4.8 or later) mock.VerifyNoOtherCalls();

Customizing Mock Behavior

Miscellaneous

Advanced Features

// get mock from a mocked instance IFoo foo = // get mock instance somehow var fooMock = Mock.Get(foo); fooMock.Setup(f => f.GetCount()).Returns(42);

// implementing multiple interfaces in mock var mock = new Mock(); var disposableFoo = mock.As(); // now the IFoo mock also implements IDisposable :) disposableFoo.Setup(disposable => disposable.Dispose());

// implementing multiple interfaces in single mock var mock = new Mock(); mock.Setup(foo => foo.Name).Returns("Fred"); mock.As().Setup(disposable => disposable.Dispose());

// custom matchers mock.Setup(foo => foo.DoSomething(IsLarge())).Throws(); ... [Matcher] public string IsLarge() { return Match.Create(s => !String.IsNullOrEmpty(s) && s.Length > 100); }


Note: When you pass the mock for consumption, you must pass mock.Object, not mock itself.

Matching Generic Type Arguments

public interface IFoo { bool M1(); bool M2(T arg); }

var mock = new Mock();

Generic arguments are matched using the usual type polymorphism rules, so if you want to match any type, you can simply use object as type argument in many cases:

mock.Setup(m => m.M1()).Returns(true);

Type matchers (Moq 4.13+)

In some situations, that might not work. Starting with Moq 4.13, you can use explicit type matchers, e.g. It.IsAnyType which is essentially a placeholder for a type (just like It.IsAny<T>() is a placeholder for any value):

// matches any type argument: mock.Setup(m => m.M1<It.IsAnyType>()).Returns(true);

// matches only type arguments that are subtypes of / implement T: mock.Setup(m => m.M1<It.IsSubtype>()).Returns(true);

// use of type matchers is allowed in the argument list: mock.Setup(m => m.M2(It.IsAny<It.IsAnyType>())).Returns(true); mock.Setup(m => m.M2(It.IsAny<It.IsSubtype>())).Returns(true);

LINQ to Mocks

Moq is the one and only mocking framework that allows specifying mock behavior via declarative specification queries. You can think of LINQ to Mocks as:

from the universe of mocks, get me one/those that behave like this (by Fernando Simonazzi)

Keep that query form in mind when reading the specifications:

var services = Mock.Of(sp => sp.GetService(typeof(IRepository)) == Mock.Of(r => r.IsAuthenticated == true) && sp.GetService(typeof(IAuthentication)) == Mock.Of(a => a.AuthenticationType == "OAuth"));

// Multiple setups on a single mock and its recursive mocks ControllerContext context = Mock.Of(ctx => ctx.HttpContext.User.Identity.Name == "kzu" && ctx.HttpContext.Request.IsAuthenticated == true && ctx.HttpContext.Request.Url == new Uri("http://moq.github.io/moq4/") && ctx.HttpContext.Response.ContentType == "application/xml");

// Setting up multiple chained mocks: var context = Mock.Of(ctx => ctx.HttpContext.Request.Url == new Uri("http://moqthis.me") && ctx.HttpContext.Response.ContentType == "application/xml" && // Chained mock specification ctx.HttpContext.GetSection("server") == Mock.Of(config => config.Server.ServerUrl == new Uri("http://moqthis.com/api")));

LINQ to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. If you do need to verify later some invocation on those mocks, you can easily retrieve them with Mock.Get(instance).