Moq
Enables the Protected() method on ,
allowing expectations to be set for protected members by using their
name as a string, rather than strong-typing them which is not possible
due to their visibility.
Enable protected expectations for the mock.
Mocked object type. Typically omitted as it can be inferred from the mock instance.
The mock to set the protected expectations on.
A strongly-typed resource class, for looking up localized strings, etc.
Returns the cached ResourceManager instance used by this class.
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
Looks up a localized string similar to Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that..
Looks up a localized string similar to Can only add interfaces to the mock..
Looks up a localized string similar to Can't set return value for void method {0}..
Looks up a localized string similar to Constructor arguments cannot be passed for interface mocks..
Looks up a localized string similar to A matching constructor for the given arguments was not found on the mocked type..
Looks up a localized string similar to Invalid expectation on a non-overridable member:
{0}.
Looks up a localized string similar to A lambda expression is expected as the argument to It.Is<T>..
Looks up a localized string similar to Expression is not a method invocation: {0}.
Looks up a localized string similar to Expression is not a method invocation or a property get: {0}.
Looks up a localized string similar to Expression is not a property access: {0}.
Looks up a localized string similar to Field calls are not supported. Use interfaces and properties instead..
Looks up a localized string similar to Type to mock must be an interface or an abstract or non-sealed class. .
Looks up a localized string similar to Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces.
Please cast the argument to one of the supported types: {1}.
Remember that there's no generics covariance in the CLR, so your object must be one of these types in order for the call to succeed..
Looks up a localized string similar to Member {0}.{1} does not exist..
Looks up a localized string similar to Method {0}.{1} is public. Use strong-typed Expect overload instead:
mock.Expect(x => x.{1}());
.
Looks up a localized string similar to {0} invocation failed with mock behavior {1}.
{2}.
Looks up a localized string similar to Expected only one call to {0}..
Looks up a localized string similar to All invocations on the mock must have a corresponding expectation..
Looks up a localized string similar to The given invocation was not performed on the mock..
Looks up a localized string similar to Object instance was not created by Moq..
Looks up a localized string similar to Property {0}.{1} does not exist..
Looks up a localized string similar to Property {0}.{1} is write-only..
Looks up a localized string similar to Property {0}.{1} is read-only..
Looks up a localized string similar to Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object..
Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding expectation that provides it..
Looks up a localized string similar to To set expectations for public property {0}.{1}, use the typed overloads, such as:
mock.Expect(x => x.{1}).Returns(value);
mock.ExpectGet(x => x.{1}).Returns(value); //equivalent to previous one
mock.ExpectSet(x => x.{1}).Callback(callbackDelegate);
.
Looks up a localized string similar to Expression {0} is not supported..
Looks up a localized string similar to Member {0} is not supported for protected mocking..
Looks up a localized string similar to To set expectations for protected property {0}.{1}, use:
mock.Expect<{2}>(x => x.{1}).Returns(value);
mock.ExpectGet(x => x.{1}).Returns(value); //equivalent to previous one
mock.ExpectSet(x => x.{1}).Callback(callbackDelegate);.
Looks up a localized string similar to The following expectations were not met:
{0}.
Allows the specification of a matching condition for an
argument in a method invocation, rather than a specific
argument value. "It" refers to the argument being matched.
This class allows the expectation to match a method invocation
with an arbitrary value, with a value in a specified range, or
even one that matches a given predicate.
Matches any value of the given type.
Typically used when the actual argument value for a method
call is not relevant.
// Throws an exception for a call to Remove with any string value.
mock.Expect(x => x.Remove(It.IsAny<string>())).Throws(new InvalidOperationException());
Type of the value.
Matches any value that satisfies the given predicate.
Type of the argument to check.
The predicate used to match the method argument.
Allows the specification of a predicate to perform matching
of method call arguments.
This example shows how to return the value 1 whenever the argument to the
Do method is an even number.
mock.Expect(x => x.Do(It.Is<int>(i => i % 2 == 0)))
.Returns(1);
This example shows how to throw an exception if the argument to the
method is a negative number:
mock.Expect(x => x.GetUser(It.Is<int>(i => i < 0)))
.Throws(new ArgumentException());
Matches any value that is in the range specified.
Type of the argument to check.
The lower bound of the range.
The upper bound of the range.
The kind of range. See .
The following example shows how to expect a method call
with an integer argument within the 0..100 range.
mock.Expect(x => x.HasInventory(
It.IsAny<string>(),
It.IsInRange(0, 100, Range.Inclusive)))
.Returns(false);
Matches a string argument if it matches the given regular expression pattern.
The pattern to use to match the string argument value.
The following example shows how to expect a call to a method where the
string argument matches the given regular expression:
mock.Expect(x => x.Check(It.IsRegex("[a-z]+"))).Returns(1);
Matches a string argument if it matches the given regular expression pattern.
The pattern to use to match the string argument value.
The options used to interpret the pattern.
The following example shows how to expect a call to a method where the
string argument matches the given regular expression, in a case insensitive way:
mock.Expect(x => x.Check(It.IsRegex("[a-z]+", RegexOptions.IgnoreCase))).Returns(1);
Provides a typed for a
specific type of .
The type of event arguments required by the event.
The mocked event can either be a or custom
event handler which follows .NET practice of providing object sender, EventArgs args
kind of signature.
Represents a generic event that has been mocked and can
be rised.
Provided solely to allow the interceptor to determine when the attached
handler is coming from this mocked event so we can assign the
corresponding EventInfo for it.
Raises the associated event with the given
event argument data.
Provides support for attaching a to
a generic event.
Event to convert.
Event raised whenever the mocked event is rised.
Raises the associated event with the given
event argument data.
Data to pass to the event.
Provides support for attaching a to
a generic event.
Event to convert.
Provided solely to allow the interceptor to determine when the attached
handler is coming from this mocked event so we can assign the
corresponding EventInfo for it.
Options to customize the behavior of the mock.
Causes the mock to always throw
an exception for invocations that don't have a
corresponding expectation.
Will never throw exceptions, returning default
values when necessary (null for reference types,
zero for value types or empty enumerables and arrays).
Default mock behavior, which equals .
Base interface for .
Helper interface used to hide the base
members from the fluent API to make it much cleaner
in Visual Studio intellisense.
Defines the Returns verb.
Type of the return value from the expression.
Specifies the value to return.
The value to return, or .
Return a true value from the method call:
mock.Expect(x => x.Execute("ping"))
.Returns(true);
Specifies a function that will calculate the value to return from the method.
The function that will calculate the return value.
Return a calculated value when the method is called:
mock.Expect(x => x.Execute("ping"))
.Returns(() => returnValues[0]);
The lambda expression to retrieve the return value is lazy-executed,
meaning that its value may change depending on the moment the method
is executed and the value the returnValues array has at
that moment.
Specifies a function that will calculate the value to return from the method,
retrieving the arguments for the invocation.
Type of the argument of the invoked method.
The function that will calculate the return value.
Return a calculated value which is evaluated lazily at the time of the invocation.
The lookup list can change between invocations and the expectation
will return different values accordingly. Also, notice how the specific
string argument is retrieved by simply declaring it as part of the lambda
expression:
mock.Expect(x => x.Execute(It.IsAny<string>()))
.Returns((string command) => returnValues[command]);
Specifies a function that will calculate the value to return from the method,
retrieving the arguments for the invocation.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
The function that will calculate the return value.
Return a calculated value which is evaluated lazily at the time of the invocation.
The return value is calculated from the value of the actual method invocation arguments.
Notice how the arguments are retrieved by simply declaring them as part of the lambda
expression:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>()))
.Returns((string arg1, string arg2) => arg1 + arg2);
Specifies a function that will calculate the value to return from the method,
retrieving the arguments for the invocation.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
The function that will calculate the return value.
Return a calculated value which is evaluated lazily at the time of the invocation.
The return value is calculated from the value of the actual method invocation arguments.
Notice how the arguments are retrieved by simply declaring them as part of the lambda
expression:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>()))
.Returns((string arg1, string arg2, int arg3) => arg1 + arg2 + arg3);
Specifies a function that will calculate the value to return from the method,
retrieving the arguments for the invocation.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
Type of the fourth argument of the invoked method.
The function that will calculate the return value.
Return a calculated value which is evaluated lazily at the time of the invocation.
The return value is calculated from the value of the actual method invocation arguments.
Notice how the arguments are retrieved by simply declaring them as part of the lambda
expression:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>(),
It.IsAny<bool>()))
.Returns((string arg1, string arg2, int arg3, bool arg4) => arg1 + arg2 + arg3 + arg4);
Checks an argument to ensure it isn't null.
The argument value to check.
The name of the argument.
Checks a string argument to ensure it isn't null or empty.
The argument value to check.
The name of the argument.
TODO: remove this code when https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=331583
is fixed.
Base class for visitors of expression trees.
Provides the functionality of the internal visitor base class that
comes with Linq.
Matt's comments on the implementation:
In this variant there is only one visitor class that dispatches calls to the general
Visit function out to specific VisitXXX methods corresponding to different node types.
Note not every node type gets it own method, for example all binary operators are
treated in one VisitBinary method. The nodes themselves do not directly participate
in the visitation process. They are treated as just data.
The reason for this is that the quantity of visitors is actually open ended.
You can write your own. Therefore no semantics of visiting is coupled into the node classes.
It’s all in the visitors. The default visit behavior for node XXX is baked into the base
class’s version of VisitXXX.
Another variant is that all VisitXXX methods return a node.
The Expression tree nodes are immutable. In order to change the tree you must construct
a new one. The default VisitXXX methods will construct a new node if any of its sub-trees change.
If no changes are made then the same node is returned. That way if you make a change
to a node (by making a new node) deep down in a tree, the rest of the tree is rebuilt
automatically for you.
See: http://blogs.msdn.com/mattwar/archive/2007/07/31/linq-building-an-iqueryable-provider-part-ii.aspx.
Matt Warren: http://blogs.msdn.com/mattwar
Documented by InSTEDD: http://www.instedd.org
Default constructor used by derived visitors.
Visits the , determining which
of the concrete Visit methods to call.
Visits the generic , determining and
calling the appropriate Visit method according to the
, which will result
in calls to ,
or .
Visits the initializer by
calling the for the
.
Visits the expression by
calling with the expression.
Visits the by calling
with the ,
and
expressions.
Visits the by calling
with the
expression.
Visits the , by default returning the
same without further behavior.
Visits the by calling
with the ,
and
expressions.
Visits the returning it
by default without further behavior.
Visits the by calling
with the
expression.
Visits the by calling
with the expression,
and then with the .
Visits the by iterating
the list and visiting each in it.
Visits the by calling
with the expression.
Visits the by calling
with the .
Visits the by calling
with the
.
Visits the by
calling for each in the
collection.
Visits the by
calling for each
in the collection.
Visits the by calling
with the expression.
Visits the by calling
with the
expressions.
Visits the by calling
with the
expression, then with the
.
Visits the by calling
with the
expression, and then with the
.
Visits the by calling
with the
expressions.
Visits the by calling
with the
expressions.
Core implementation of the interface.
Type to mock.
Base class for mocks and static helper class with methods that
apply to mocked objects, such as to
retrieve a from an object instance.
Base mock interface exposing non-generic members.
Creates a handler that can be associated to an event receiving
the given and can be used
to raise the event.
Type of
data passed in to the event.
This example shows how to invoke an event with a custom event arguments
class in a view that will cause its corresponding presenter to
react by changing its state:
var mockView = new Mock<IOrdersView>();
var mockedEvent = mockView.CreateEventHandler<OrderEventArgs>();
var presenter = new OrdersPresenter(mockView.Object);
// Check that the presenter has no selection by default
Assert.Null(presenter.SelectedOrder);
// Create a mock event handler of the appropriate type
var handler = mockView.CreateEventHandler<OrderEventArgs>();
// Associate it with the event we want to raise
mockView.Object.Cancel += handler;
// Finally raise the event with a specific arguments data
handler.Raise(new OrderEventArgs { Order = new Order("moq", 500) });
// Now the presenter reacted to the event, and we have a selected order
Assert.NotNull(presenter.SelectedOrder);
Assert.Equal("moq", presenter.SelectedOrder.ProductName);
Creates a handler that can be associated to an event receiving
a generic and can be used
to raise the event.
This example shows how to invoke a generic event in a view that will
cause its corresponding presenter to react by changing its state:
var mockView = new Mock<IOrdersView>();
var mockedEvent = mockView.CreateEventHandler();
var presenter = new OrdersPresenter(mockView.Object);
// Check that the presenter is not in the "Canceled" state
Assert.False(presenter.IsCanceled);
// Create a mock event handler of the appropriate type
var handler = mockView.CreateEventHandler();
// Associate it with the event we want to raise
mockView.Object.Cancel += handler;
// Finally raise the event
handler.Raise(EventArgs.Empty);
// Now the presenter reacted to the event, and changed its state
Assert.True(presenter.IsCanceled);
Verifies that all verifiable expectations have been met.
This example sets up an expectation and marks it as verifiable. After
the mock is used, a call is issued on the mock
to ensure the method in the expectation was invoked:
var mock = new Mock<IWarehouse>();
mock.Expect(x => x.HasInventory(TALISKER, 50)).Verifiable().Returns(true);
...
// other test code
...
// Will throw if the test code has didn't call HasInventory.
mock.Verify();
Not all verifiable expectations were met.
Verifies all expectations regardless of whether they have
been flagged as verifiable.
This example sets up an expectation without marking it as verifiable. After
the mock is used, a call is issued on the mock
to ensure that all expectations are met:
var mock = new Mock<IWarehouse>();
mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true);
...
// other test code
...
// Will throw if the test code has didn't call HasInventory, even
// that expectation was not marked as verifiable.
mock.VerifyAll();
At least one expectation was not met.
Whether the base member virtual implementation will be called
for mocked classes if no expectation is met. Defaults to .
The mocked object instance.
Retrieves the mock object for the given object instance.
Type of the mock to retrieve. Can be omitted as it's inferred
from the object instance passed in as the instance.
The instance of the mocked object.
The mock associated with the mocked object.
The received instance
was not created by Moq.
The following example shows how to add a new expectation to an object
instance which is not the original but rather
the object associated with it:
// Typed instance, not the mock, is retrieved from some test API.
HttpContextBase context = GetMockContext();
// context.Request is the typed object from the "real" API
// so in order to add an expectation to it, we need to get
// the mock that "owns" it
Mock<HttpRequestBase> request = Mock.Get(context.Request);
mock.Expect(req => req.AppRelativeCurrentExecutionFilePath)
.Returns(tempUrl);
Initializes the mock
Returns the mocked object value.
Implements .
Implements .
Implements .
Type of event argument class.
Implements
Base class for mocks and static helper class with methods that
apply to mocked objects, such as to
retrieve a from an object instance.
Exposes the list of extra interfaces implemented by the mock.
Implements .
The mocked object instance. Implements .
Type to mock, which can be an interface or a class.
Provides a mock implementation of .
Only abstract and virtual members of classes can be mocked.
The behavior of the mock with regards to the expectations and the actual calls is determined
by the optional that can be passed to the
constructor.
The following example shows setting expectations with specific values
for method invocations:
//setup - data
var order = new Order(TALISKER, 50);
var mock = new Mock<IWarehouse>();
//setup - expectations
mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true);
//exercise
order.Fill(mock.Object);
//verify
Assert.True(order.IsFilled);
The following example shows how to use the class
to specify conditions for arguments instead of specific values:
//setup - data
var order = new Order(TALISKER, 50);
var mock = new Mock<IWarehouse>();
//setup - expectations
//shows how to expect a value within a range
mock.Expect(x => x.HasInventory(
It.IsAny<string>(),
It.IsInRange(0, 100, Range.Inclusive)))
.Returns(false);
//shows how to throw for unexpected calls. contrast with the "verify" approach of other mock libraries.
mock.Expect(x => x.Remove(
It.IsAny<string>(),
It.IsAny<int>()))
.Throws(new InvalidOperationException());
//exercise
order.Fill(mock.Object);
//verify
Assert.False(order.IsFilled);
Adds an interface implementation to the mock,
allowing expectations to be set for it.
This method can only be called before the first use
of the mock property, at which
point the runtime type has already been generated
and no more interfaces can be added to it.
Also, must be an
interface and not a class, which must be specified
when creating the mock instead.
The mock type
has already been generated by accessing the property.
The specified
is not an interface.
The following example creates a mock for the main interface
and later adds to it to verify
it's called by the consumer code:
var mock = new Mock<IProcessor>();
mock.Expect(x => x.Execute("ping"));
// add IDisposable interface
var disposable = mock.As<IDisposable>();
disposable.Expect(d => d.Dispose()).Verifiable();
Type of interface to cast the mock to.
Sets an expectation on the mocked type for a call to
to a value returning method.
Type of the return value. Typically omitted as it can be inferred from the expression.
If more than one expectation is set for the same method or property,
the latest one wins and is the one that will be executed.
Lambda expression that specifies the expected method invocation.
mock.Expect(x => x.HasInventory("Talisker", 50)).Returns(true);
Sets an expectation on the mocked type for a call to
to a void method.
If more than one expectation is set for the same method or property,
the latest one wins and is the one that will be executed.
Lambda expression that specifies the expected method invocation.
var mock = new Mock<IProcessor>();
mock.Expect(x => x.Execute("ping"));
Sets an expectation on the mocked type for a call to
to a property getter.
If more than one expectation is set for the same property getter,
the latest one wins and is the one that will be executed.
Type of the property. Typically omitted as it can be inferred from the expression.
Lambda expression that specifies the expected property getter.
mock.ExpectGet(x => x.Suspended)
.Returns(true);
Sets an expectation on the mocked type for a call to
to a property setter.
If more than one expectation is set for the same property setter,
the latest one wins and is the one that will be executed.
Type of the property. Typically omitted as it can be inferred from the expression.
Lambda expression that specifies the expected property setter.
mock.ExpectSet(x => x.Suspended);
Implements .
Implements .
Verifies that a specific invocation matching the given
expression was performed on the mock. Use in conjuntion
with the default .
This example assumes that the mock has been used,
and later we want to verify that a given invocation
with specific parameters was performed:
var mock = new Mock<IProcessor>();
// exercise mock
//...
// Will throw if the test code didn't call Execute with a "ping" string argument.
mock.Verify(proc => proc.Execute("ping"));
The invocation was not performed on the mock.
Expression to verify.
Verifies that a specific invocation matching the given
expression was performed on the mock. Use in conjuntion
with the default .
This example assumes that the mock has been used,
and later we want to verify that a given invocation
with specific parameters was performed:
var mock = new Mock<IWarehouse>();
// exercise mock
//...
// Will throw if the test code didn't call HasInventory.
mock.Verify(warehouse => warehouse.HasInventory(TALISKER, 50));
The invocation was not performed on the mock.
Expression to verify.
Type of return value from the expression.
Verifies that a property was read on the mock.
Use in conjuntion with the default .
This example assumes that the mock has been used,
and later we want to verify that a given property
was retrieved from it:
var mock = new Mock<IWarehouse>();
// exercise mock
//...
// Will throw if the test code didn't retrieve the IsClosed property.
mock.VerifyGet(warehouse => warehouse.IsClosed);
The invocation was not performed on the mock.
Expression to verify.
Type of the property to verify. Typically omitted as it can
be inferred from the expression's return type.
Verifies that a property has been set on the mock.
Use in conjuntion with the default .
This example assumes that the mock has been used,
and later we want to verify that a given invocation
with specific parameters was performed:
var mock = new Mock<IWarehouse>();
// exercise mock
//...
// Will throw if the test code didn't set the IsClosed property.
mock.VerifySet(warehouse => warehouse.IsClosed);
The invocation was not performed on the mock.
Expression to verify.
Type of the property to verify. Typically omitted as it can
be inferred from the expression's return type.
Exposes the mocked object instance.
Initializes an instance of the mock with a specific behavior with
the given constructor arguments for the class.
The mock will try to find the best match constructor given the constructor arguments, and invoke that
to initialize the instance. This applies only to classes, not interfaces.
var mock = new Mock<MyProvider>(someArgument, 25);
Behavior of the mock.
Optional constructor arguments if the mocked type is a class.
Initializes an instance of the mock with default behavior and with
the given constructor arguments for the class. (Only valid when is a class)
The mock will try to find the best match constructor given the constructor arguments, and invoke that
to initialize the instance. This applies only for classes, not interfaces.
var mock = new Mock<MyProvider>(someArgument, 25);
Optional constructor arguments if the mocked type is a class.
Initializes an instance of the mock with default behavior.
var mock = new Mock<IFormatProvider>();
Initializes an instance of the mock with the specified behavior.
var mock = new Mock<IFormatProvider>(MockBehavior.Relaxed);
Behavior of the mock.
Returns the mocked object value.
Implements .
Lambda expression that specifies the expected method invocation.
Implements .
Type of the return value. Typically omitted as it can be inferred from the expression.
Lambda expression that specifies the expected method invocation.
Implements .
Type of the property. Typically omitted as it can be inferred from the expression.
Lambda expression that specifies the expected property getter.
Implements .
Type of the property. Typically omitted as it can be inferred from the expression.
Lambda expression that specifies the expected property setter.
Implements .
Expression to verify.
Implements .
Expression to verify.
Type of return value from the expression.
Implements .
Expression to verify.
Type of the property to verify. Typically omitted as it can
be inferred from the expression's return type.
Implements .
Expression to verify.
Type of the property to verify. Typically omitted as it can
be inferred from the expression's return type.
Implements .
Implements .
Implements .
Type of interface to cast the mock to.
Exposes the mocked object instance.
Used for testing the mock factory.
Defines the Returns verb for property get expectations.
Type of the property.
Specifies the value to return.
The value to return, or .
Return a true value from the property getter call:
mock.ExpectGet(x => x.Suspended)
.Returns(true);
Specifies a function that will calculate the value to return for the property.
The function that will calculate the return value.
Return a calculated value when the property is retrieved:
mock.ExpectGet(x => x.Suspended)
.Returns(() => returnValues[0]);
The lambda expression to retrieve the return value is lazy-executed,
meaning that its value may change depending on the moment the property
is retrieved and the value the returnValues array has at
that moment.
Allows the specification of a matching condition for an
argument in a protected member expectation, rather than a specific
argument value. "ItExpr" refers to the argument being matched.
Use this variant of argument matching instead of
for protected expectations.
This class allows the expectation to match a method invocation
with an arbitrary value, with a value in a specified range, or
even one that matches a given predicate.
Matches any value of the given type.
Typically used when the actual argument value for a method
call is not relevant.
// Throws an exception for a call to Remove with any string value.
mock.Protected()
.Expect("Remove", ItExpr.IsAny<string>())
.Throws(new InvalidOperationException());
Type of the value.
Matches any value that satisfies the given predicate.
Type of the argument to check.
The predicate used to match the method argument.
Allows the specification of a predicate to perform matching
of method call arguments.
This example shows how to return the value 1 whenever the argument to the
Do method is an even number.
mock.Protected()
.Expect("Do", ItExpr.Is<int>(i => i % 2 == 0))
.Returns(1);
This example shows how to throw an exception if the argument to the
method is a negative number:
mock.Protected()
.Expect("GetUser", ItExpr.Is<int>(i => i < 0))
.Throws(new ArgumentException());
Matches any value that is in the range specified.
Type of the argument to check.
The lower bound of the range.
The upper bound of the range.
The kind of range. See .
The following example shows how to expect a method call
with an integer argument within the 0..100 range.
mock.Protected()
.Expect("HasInventory",
ItExpr.IsAny<string>(),
ItExpr.IsInRange(0, 100, Range.Inclusive))
.Returns(false);
Matches a string argument if it matches the given regular expression pattern.
The pattern to use to match the string argument value.
The following example shows how to expect a call to a method where the
string argument matches the given regular expression:
mock.Protected()
.Expect("Check", ItExpr.IsRegex("[a-z]+"))
.Returns(1);
Matches a string argument if it matches the given regular expression pattern.
The pattern to use to match the string argument value.
The options used to interpret the pattern.
The following example shows how to expect a call to a method where the
string argument matches the given regular expression, in a case insensitive way:
mock.Protected()
.Expect("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase))
.Returns(1);
Implements the fluent API.
Defines the Callback verb and overloads.
Specifies a callback to invoke when the method is called.
Callback method to invoke.
The following example specifies a callback to set a boolean
value that can be used later:
bool called = false;
mock.Expect(x => x.Execute())
.Callback(() => called = true);
Specifies a callback to invoke when the method is called that receives the original
arguments.
Argument type of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation argument value.
Notice how the specific string argument is retrieved by simply declaring
it as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(It.IsAny<string>()))
.Callback((string command) => Console.WriteLine(command));
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>()))
.Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2));
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>()))
.Callback((string arg1, string arg2, int arg3) => Console.WriteLine(arg1 + arg2 + arg3));
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
Type of the fourth argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>(),
It.IsAny<bool>()))
.Callback((string arg1, string arg2, int arg3, bool arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4));
Implements the fluent API.
Defines the Throws verb.
Specifies the exception to throw when the method is invoked.
Exception instance to throw.
This example shows how to throw an exception when the method is
invoked with an empty string argument:
mock.Expect(x => x.Execute(""))
.Throws(new ArgumentException());
Specifies the type of exception to throw when the method is invoked.
Type of exception to instantiate and throw when the expectation is met.
This example shows how to throw an exception when the method is
invoked with an empty string argument:
mock.Expect(x => x.Execute(""))
.Throws<ArgumentException>();
Implements the fluent API.
Defines occurrence members to constraint expectations.
The expected invocation can happen at most once.
var mock = new Mock<ICommand>();
mock.Expect(foo => foo.Execute("ping"))
.AtMostOnce();
Defines the Verifiable verb.
Marks the expectation as verifiable, meaning that a call
to will check if this particular
expectation was met.
The following example marks the expectation as verifiable:
mock.Expect(x => x.Execute("ping"))
.Returns(true)
.Verifiable();
Defines the Raises verb.
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
The event args to pass when raising the event.
The following example shows how to set an expectation that will
raise an event when it's met:
var mock = new Mock<IContainer>();
// create handler to associate with the event to raise
var handler = mock.CreateEventHandler();
// associate the handler with the event to raise
mock.Object.Added += handler;
// set the expectation and the handler to raise
mock.Expect(add => add.Add(It.IsAny<string>(), It.IsAny<object>()))
.Raises(handler, EventArgs.Empty);
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
A function that will build the
to pass when raising the event.
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
A function that will build the
to pass when raising the event.
Type of the argument received by the expected invocation.
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
A function that will build the
to pass when raising the event.
Type of the first argument received by the expected invocation.
Type of the second argument received by the expected invocation.
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
A function that will build the
to pass when raising the event.
Type of the first argument received by the expected invocation.
Type of the second argument received by the expected invocation.
Type of the third argument received by the expected invocation.
Specifies the mocked event that will be raised
when the expectation is met.
The mocked event, retrieved from
or .
A function that will build the
to pass when raising the event.
Type of the first argument received by the expected invocation.
Type of the second argument received by the expected invocation.
Type of the third argument received by the expected invocation.
Type of the fourth argument received by the expected invocation.
Implements the fluent API.
Defines the Callback verb for property setter expectations.
Type of the property.
Specifies a callback to invoke when the property is set that receives the
property value being set.
Callback method to invoke.
Invokes the given callback with the property value being set.
mock.ExpectSet(x => x.Suspended)
.Callback((bool state) => Console.WriteLine(state));
Implements the actual interception and method invocation for
all mocks.
Get an eventInfo for a given event name. Search type ancestors depth first if necessary.
Name of the event, with the set_ or get_ prefix already removed
Given a type return all of its ancestors, both types and interfaces.
The type to find immediate ancestors of
Provides partial evaluation of subtrees, whenever they can be evaluated locally.
Matt Warren: http://blogs.msdn.com/mattwar
Documented by InSTEDD: http://www.instedd.org
Performs evaluation and replacement of independent sub-trees
The root of the expression tree.
A function that decides whether a given expression
node can be part of the local function.
A new tree with sub-trees evaluated and replaced.
Performs evaluation and replacement of independent sub-trees
The root of the expression tree.
A new tree with sub-trees evaluated and replaced.
Evaluates and replaces sub-trees when first candidate is reached (top-down)
Performs bottom-up analysis to determine which nodes can possibly
be part of an evaluated sub-tree.
Implements the fluent API.
Allows expectations to be set for protected members by using their
name as a string, rather than strong-typing them which is not possible
due to their visibility.
Sets an expectation on the void method with the given
, optionally specifying
arguments for the method call.
Name of the void method to be invoke.
Optional arguments for the invocation.
Sets an expectation on a property or a non void method with the given
, optionally specifying
arguments for the method call.
Name of the method or property to be invoke.
Optional arguments for the invocation.
Return type of the method or property.
Sets an expectation on a property getter with the given
.
Name of the property.
Type of the property.
Sets an expectation on a property setter with the given
.
Name of the property.
Type of the property.
Utility factory class to use to construct multiple
mocks when consistent verification is
desired for all of them.
If multiple mocks will be created during a test, passing
the desired (if different than the
or the one
passed to the factory constructor) and later verifying each
mock can become repetitive and tedious.
This factory class helps in that scenario by providing a
simplified creation of multiple mocks with a default
(unless overriden by calling
) and posterior verification.
The following is a straightforward example on how to
create and automatically verify strict mocks using a :
var factory = new MockFactory(MockBehavior.Strict);
var foo = factory.Create<IFoo>();
var bar = factory.Create<IBar>();
// no need to call Verifiable() on the expectation
// as we'll be validating all expectations anyway.
foo.Expect(f => f.Do());
bar.Expect(b => b.Redo());
// exercise the mocks here
factory.VerifyAll();
// At this point all expectations are already checked
// and an optional MockException might be thrown.
// Note also that because the mocks are strict, any invocation
// that doesn't have a matching expectation will also throw a MockException.
The following examples shows how to setup the factory
to create loose mocks and later verify only verifiable expectations:
var factory = new MockFactory(MockBehavior.Loose);
var foo = factory.Create<IFoo>();
var bar = factory.Create<IBar>();
// this expectation will be verified at the end of the "using" block
foo.Expect(f => f.Do()).Verifiable();
// this expectation will NOT be verified
foo.Expect(f => f.Calculate());
// this expectation will be verified at the end of the "using" block
bar.Expect(b => b.Redo()).Verifiable();
// exercise the mocks here
// note that because the mocks are Loose, members
// called in the interfaces for which no matching
// expectations exist will NOT throw exceptions,
// and will rather return default values.
factory.Verify();
// At this point verifiable expectations are already checked
// and an optional MockException might be thrown.
The following examples shows how to setup the factory with a
default strict behavior, overriding that default for a
specific mock:
var factory = new MockFactory(MockBehavior.Strict);
// this particular one we want loose
var foo = factory.Create<IFoo>(MockBehavior.Loose);
var bar = factory.Create<IBar>();
// set expectations
// exercise the mocks here
factory.Verify();
Initializes the factory with the given
for newly created mocks from the factory.
The behavior to use for mocks created
using the factory method if not overriden
by using the overload.
Creates a new mock with the default
specified at factory construction time.
Type to mock.
A new .
var factory = new MockFactory(MockBehavior.Strict);
var foo = factory.Create<IFoo>();
// use mock on tests
factory.VerifyAll();
Creates a new mock with the default
specified at factory construction time and with the
the given constructor arguments for the class.
The mock will try to find the best match constructor given the
constructor arguments, and invoke that to initialize the instance.
This applies only to classes, not interfaces.
Type to mock.
Constructor arguments for mocked classes.
A new .
var factory = new MockFactory(MockBehavior.Default);
var mock = factory.Create<MyBase>("Foo", 25, true);
// use mock on tests
factory.Verify();
Creates a new mock with the given .
Type to mock.
Behavior to use for the mock, which overrides
the default behavior specified at factory construction time.
A new .
The following example shows how to create a mock with a different
behavior to that specified as the default for the factory:
var factory = new MockFactory(MockBehavior.Strict);
var foo = factory.Create<IFoo>(MockBehavior.Loose);
Creates a new mock with the given
and with the the given constructor arguments for the class.
The mock will try to find the best match constructor given the
constructor arguments, and invoke that to initialize the instance.
This applies only to classes, not interfaces.
Type to mock.
Behavior to use for the mock, which overrides
the default behavior specified at factory construction time.
Constructor arguments for mocked classes.
A new .
The following example shows how to create a mock with a different
behavior to that specified as the default for the factory, passing
constructor arguments:
var factory = new MockFactory(MockBehavior.Default);
var mock = factory.Create<MyBase>(MockBehavior.Strict, "Foo", 25, true);
Implements creation of a new mock within the factory.
Type to mock.
The behavior for the new mock.
Optional arguments for the construction of the mock.
Verifies all verifiable expectations on all mocks created
by this factory.
One or more mocks had expectations that were not satisfied.
Verifies all verifiable expectations on all mocks created
by this factory.
One or more mocks had expectations that were not satisfied.
Invokes for each mock
in , and accumulates the resulting
that might be
thrown from the action.
The action to execute against
each mock.
Gets the mocks that have been created by this factory and
that will get verified together.
Represents the default value returned from invocations that
do not have expectations or return values, with loose mocks.
Matcher to treat static functions as matchers.
mock.Expect(x => x.StringMethod(A.MagicString()));
pbulic static class A
{
[Matcher]
public static string MagicString() { return null; }
public static bool MagicString(string arg)
{
return arg == "magic";
}
}
Will success if: mock.Object.StringMethod("magic");
and fail with any other call.
Implements the fluent API.
Defines the Callback verb and overloads for callbacks on
expectations that return a value.
Type of the return value of the expectation.
Specifies a callback to invoke when the method is called.
Callback method to invoke.
The following example specifies a callback to set a boolean
value that can be used later:
bool called = false;
mock.Expect(x => x.Execute())
.Callback(() => called = true)
.Returns(true);
Note that in the case of value-returning methods, after the Callback
call you can still specify the return value.
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation argument value.
Notice how the specific string argument is retrieved by simply declaring
it as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(It.IsAny<string>()))
.Callback((string command) => Console.WriteLine(command))
.Returns(true);
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>()))
.Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2))
.Returns(true);
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>()))
.Callback((string arg1, string arg2, int arg3) => Console.WriteLine(arg1 + arg2 + arg3))
.Returns(true);
Specifies a callback to invoke when the method is called that receives the original
arguments.
Type of the first argument of the invoked method.
Type of the second argument of the invoked method.
Type of the third argument of the invoked method.
Type of the fourth argument of the invoked method.
Callback method to invoke.
Invokes the given callback with the concrete invocation arguments values.
Notice how the specific arguments are retrieved by simply declaring
them as part of the lambda expression for the callback:
mock.Expect(x => x.Execute(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<int>(),
It.IsAny<bool>()))
.Callback((string arg1, string arg2, int arg3, bool arg4) => Console.WriteLine(arg1 + arg2 + arg3 + arg4))
.Returns(true);
Implements the fluent API.
Implements the fluent API.
Defines the Callback verb for property getter expectations.
Type of the property.
Specifies a callback to invoke when the property is retrieved.
Callback method to invoke.
Invokes the given callback with the property value being set.
mock.ExpectGet(x => x.Suspended)
.Callback(() => called = true)
.Returns(true);
Implements the fluent API.
Implemented by all generated mock object instances.
Implemented by all generated mock object instances.
Reference the Mock that contains this as the mock.Object value.
Reference the Mock that contains this as the mock.Object value.
Marks a method as a matcher, which allows complete replacement
of the built-in class with your own argument
matching rules.
The argument matching is used to determine whether a concrete
invocation in the mock matches a given expectation. This
matching mechanism is fully extensible.
There are two parts of a matcher: the compiler matcher
and the runtime matcher.
-
Compiler matcher
Used to satisfy the compiler requirements for the
argument. Needs to be a method optionally receiving any arguments
you might need for the matching, but with a return type that
matches that of the argument.
Let's say I want to match a lists of orders that contains
a particular one. I might create a compiler matcher like the following:
public static class Orders
{
[Matcher]
public static IEnumerable<Order> Contains(Order order)
{
return null;
}
}
Now we can invoke this static method instead of an argument in an
invocation:
var order = new Order { ... };
var mock = new Mock<IRepository<Order>>();
mock.Expect(x => x.Save(Orders.Contains(order)))
.Throws<ArgumentException>();
Note that the return value from the compiler matcher is irrelevant.
This method will never be called, and is just used to satisfy the
compiler and to signal Moq that this is not a method that we want
to be invoked at runtime.
-
Runtime matcher
The runtime matcher is the one that will actually perform evaluation
when the test is run, and is defined by convention to have the
same signature as the compiler matcher, but where the return
value is the first argument to the call, which contains the
object received by the actual invocation at runtime:
public static bool Contains(IEnumerable<Order> orders, Order order)
{
return orders.Contains(order);
}
At runtime, the mocked method will be invoked with a specific
list of orders. This value will be passed to this runtime
matcher as the first argument, while the second argument is the
one specified in the expectation (x.Save(Orders.Contains(order))).
The boolean returned determines whether the given argument has been
matched. If all arguments to the expected method are matched, then
the expectation is verified.
Using this extensible infrastructure, you can easily replace the entire
set of matchers with your own. You can also avoid the
typical (and annoying) lengthy expressions that result when you have
multiple arguments that use generics.
The following is the complete example explained above:
public static class Orders
{
[Matcher]
public static IEnumerable<Order> Contains(Order order)
{
return null;
}
public static bool Contains(IEnumerable<Order> orders, Order order)
{
return orders.Contains(order);
}
}
And the concrete test using this matcher:
var order = new Order { ... };
var mock = new Mock<IRepository<Order>>();
mock.Expect(x => x.Save(Orders.Contains(order)))
.Throws<ArgumentException>();
// use mock, invoke Save, and have the matcher filter.
Kind of range to use in a filter specified through
.
The range includes the to and
from values.
The range does not include the to and
from values.
We need this non-generics base class so that
we can use from
generic code.
Exception thrown by mocks when expectations are not met,
the mock is not properly setup, etc.
A distinct exception type is provided so that exceptions
thrown by the mock can be differentiated in tests that
expect other exceptions to be thrown (i.e. ArgumentException).
Richer exception hierarchy/types are not provided as
tests typically should not catch or expect exceptions
from the mocks. These are typically the result of changes
in the tested class or its collaborators implementation, and
result in fixes in the mock setup so that they dissapear and
allow the test to pass.
Supports the serialization infrastructure.
Serialization information.
Streaming context.
Supports the serialization infrastructure.
Serialization information.
Streaming context.
Made internal as it's of no use for
consumers, but it's important for
our own tests.
Used by the mock factory to accumulate verification
failures.
Supports the serialization infrastructure.