Moq A that returns an empty default value for invocations that do not have setups or return values, with loose mocks. This is the default behavior for a mock. Interface to be implemented by classes that determine the default value of non-expected invocations. Provides a value for the given member and arguments. The member to provide a default value for. Optional arguments passed in to the call that requires a default value. Implements the fluent API. Defines the Callback verb and overloads. Helper interface used to hide the base members from the fluent API to make it much cleaner in Visual Studio intellisense. 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.Setup(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.Setup(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.Setup(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.Setup(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.Setup(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)); Defines occurrence members to constraint setups. The expected invocation can happen at most once. var mock = new Mock<ICommand>(); mock.Setup(foo => foo.Execute("ping")) .AtMostOnce(); The expected invocation can happen at most specified number of times. The number of times to accept calls. var mock = new Mock<ICommand>(); mock.Setup(foo => foo.Execute("ping")) .AtMost( 5 ); Defines the Raises verb. Specifies the event that will be raised when the setup is met. An expression that represents an event attach or detach action. The event arguments to pass for the raised event. The following example shows how to raise an event when the setup is met: var mock = new Mock<IContainer>(); mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) .Raises(add => add.Added += null, EventArgs.Empty); Specifies the event that will be raised when the setup is matched. An expression that represents an event attach or detach action. A function that will build the to pass when raising the event. Specifies the event that will be raised when the setup is matched. An expression that represents an event attach or detach action. A function that will build the to pass when raising the event. Type of the argument received by the expected invocation. Specifies the event that will be raised when the setup is matched. An expression that represents an event attach or detach action. 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 event that will be raised when the setup is matched. An expression that represents an event attach or detach action. 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 event that will be raised when the setup is matched. An expression that represents an event attach or detach action. 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. Specifies the custom event that will be raised when the setup is matched. An expression that represents an event attach or detach action. The arguments to pass to the custom delegate (non EventHandler-compatible). Defines the Raises verb. Specifies the mocked event that will be raised when the setup is met. The mocked event, retrieved from or . The event args to pass when raising the event. The following example shows how to raise an event when the setup is 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; // setup the invocation and the handler to raise mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) .Raises(handler, EventArgs.Empty); Specifies the mocked event that will be raised when the setup is matched. 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 setup is matched. 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 setup is matched. 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 setup is matched. 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 setup is matched. 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. 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(); Marks the expectation as verifiable, meaning that a call to will check if this particular expectation was met, and specifies a message for failures. The following example marks the expectation as verifiable: mock.Expect(x => x.Execute("ping")) .Returns(true) .Verifiable("Ping should be executed always!"); Marks a method as a matcher, which allows complete replacement of the built-in class with your own argument matching rules. This feature has been deprecated in favor of the new and simpler . The argument matching is used to determine whether a concrete invocation in the mock matches a given setup. 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.Setup(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 setup (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 setup matches and is evaluated. 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.Setup(x => x.Save(Orders.Contains(order))) .Throws<ArgumentException>(); // use mock, invoke Save, and have the matcher filter. Casts the expression to a lambda expression, removing a cast if there's any. Casts the body of the lambda expression to a . If the body is not a method call. Converts the body of the lambda expression into the referenced by it. Checks whether the body of the lambda expression is a property access. Checks whether the expression is a property access. Checks whether the body of the lambda expression is a property indexer, which is true when the expression is an whose has equal to . Checks whether the expression is a property indexer, which is true when the expression is an whose has equal to . Creates an expression that casts the given expression to the type. 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. 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. 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. Checks an argument to ensure it is in the specified range including the edges. Type of the argument to check, it must be an type. The argument value to check. The minimun allowed value for the argument. The maximun allowed value for the argument. The name of the argument. Checks an argument to ensure it is in the specified range excluding the edges. Type of the argument to check, it must be an type. The argument value to check. The minimun allowed value for the argument. The maximun allowed value for the argument. The name of the argument. Defines the Returns verb for property get setups. Mocked type. Type of the property. Specifies the value to return. The value to return, or . Return a true value from the property getter call: mock.SetupGet(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.SetupGet(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. Defines the Callback verb for property getter setups. Mocked type. 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.SetupGet(x => x.Suspended) .Callback(() => called = true) .Returns(true); Implements the fluent API. Implements the fluent API. Defines the Returns verb. Mocked type. 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.Setup(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.Setup(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 setup 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.Setup(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.Setup(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.Setup(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.Setup(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); 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.Setup(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 setup is matched. This example shows how to throw an exception when the method is invoked with an empty string argument: mock.Setup(x => x.Execute("")) .Throws<ArgumentException>(); Implements the fluent API. Implements the fluent API. Defines the Callback verb and overloads for callbacks on setups that return a value. Mocked type. Type of the return value of the setup. 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.Setup(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.Setup(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.Setup(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.Setup(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.Setup(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); 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. 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 Implements the fluent API. Defines the Never verb. The expected invocation is never expected to happen. var mock = new Mock<ICommand>(); mock.Setup(foo => foo.Execute("ping")) .Never(); is always verified inmediately as the invocations are performed, like strict mocks do with unexpected invocations. Implements the fluent API. Implements the fluent API. Implements the fluent API. Defines the Callback verb for property setter setups. 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.SetupSet(x => x.Suspended) .Callback((bool state) => Console.WriteLine(state)); 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 setup 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.Setup(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.Setup(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.Setup(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.Setup(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.Setup(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.Setup(x => x.Check(It.IsRegex("[a-z]+", RegexOptions.IgnoreCase))).Returns(1); Matcher to treat static functions as matchers. mock.Setup(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. We need this non-generics base class so that we can use from generic code. Base class for mocks and static helper class with methods that apply to mocked objects, such as to retrieve a from an 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 setup 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 a setup to it, we need to get // the mock that "owns" it Mock<HttpRequestBase> request = Mock.Get(context.Request); mock.Setup(req => req.AppRelativeCurrentExecutionFilePath) .Returns(tempUrl); Returns the mocked object value. 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 Verify() call is issued on the mock to ensure the method in the setup was invoked: var mock = new Mock<IWarehouse>(); this.Setup(x => x.HasInventory(TALISKER, 50)).Verifiable().Returns(true); ... // other test code ... // Will throw if the test code has didn't call HasInventory. this.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>(); this.Setup(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. this.VerifyAll(); At least one expectation was not met. Gets the interceptor target for the given expression and root mock, building the intermediate hierarchy of mock objects if necessary. 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); Base class for mocks and static helper class with methods that apply to mocked objects, such as to retrieve a from an object instance. Behavior of the mock, according to the value set in the constructor. Whether the base member virtual implementation will be called for mocked classes if no setup is matched. Defaults to . Specifies the behavior to use when returning default values for unexpected invocations on loose mocks. Gets the mocked object instance, which is of the mocked type . Retrieves the type of the mocked object, its generic type argument. This is used in the auto-mocking of hierarchy access. Specifies the class that will determine the default value to return when invocations are made that have no setups and need to return a default value (for loose mocks). Exposes the list of extra interfaces implemented by the mock. Options to customize the behavior of the mock. Causes the mock to always throw an exception for invocations that don't have a corresponding setup. 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 . 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. 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. Exception thrown by mocks when setups are not matched, 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. 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 setup // as we'll be validating all of them anyway. foo.Setup(f => f.Do()); bar.Setup(b => b.Redo()); // exercise the mocks here factory.VerifyAll(); // At this point all setups 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 setup will also throw a MockException. The following examples shows how to setup the factory to create loose mocks and later verify only verifiable setups: var factory = new MockFactory(MockBehavior.Loose); var foo = factory.Create<IFoo>(); var bar = factory.Create<IBar>(); // this setup will be verified when we verify the factory foo.Setup(f => f.Do()).Verifiable(); // this setup will NOT be verified foo.Setup(f => f.Calculate()); // this setup will be verified when we verify the factory bar.Setup(b => b.Redo()).Verifiable(); // exercise the mocks here // note that because the mocks are Loose, members // called in the interfaces for which no matching // setups exist will NOT throw exceptions, // and will rather return default values. factory.Verify(); // At this point verifiable setups 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>(); // specify setups // 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. Whether the base member virtual implementation will be called for mocked classes if no setup is matched. Defaults to . Specifies the behavior to use when returning default values for unexpected invocations on loose mocks. Gets the mocks that have been created by this factory and that will get verified together. 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 Value cannot be an empty string.. 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 Expression {0} involves a field access, which is not supported. Use 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.Setup(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 {0} calls to {1}.. Looks up a localized string similar to Expected only one call to {0}.. Looks up a localized string similar to {0} Invocation was performed on the mock less than {2} times: {1}. Looks up a localized string similar to {0} Invocation was not performed on the mock: {1}. Looks up a localized string similar to {0} Invocation was performed on the mock more than {3} times: {1}. Looks up a localized string similar to {0} Invocation was performed on the mock more than once: {1}. Looks up a localized string similar to {0} Invocation was performed on the mock less or equal than {2} times or more or equal than {3} times: {1}. Looks up a localized string similar to {0} Invocation was performed on the mock less than {2} times or more than {3} times: {1}. Looks up a localized string similar to {0} Invocation was not performed on the mock {2} times: {1}. Looks up a localized string similar to {0} Invocation should not have been performed on the mock: {1}. Looks up a localized string similar to {0} Invocation was performed more than once on the mock: {1}. Looks up a localized string similar to All invocations on the mock must have a corresponding setup.. 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 setup that provides it.. 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 Invocation {0} should not have been made.. 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 property access: {0}. Looks up a localized string similar to Expression is not a property setter invocation.. Looks up a localized string similar to Invalid setup on a non-overridable member: {0}. Looks up a localized string similar to Type {0} does not implement required interface {1}. Looks up a localized string similar to Type {0} does not from required type {1}. Looks up a localized string similar to To specify a setup for public property {0}.{1}, use the typed overloads, such as: mock.Setup(x => x.{1}).Returns(value); mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one mock.SetupSet(x => x.{1}).Callback(callbackDelegate); . Looks up a localized string similar to Expression {0} is not supported.. Looks up a localized string similar to Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}.. Looks up a localized string similar to Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}.. Looks up a localized string similar to Setter expression cannot use argument matchers that receive parameters.. Looks up a localized string similar to Member {0} is not supported for protected mocking.. Looks up a localized string similar to Setter expression can only use static custom matchers.. Looks up a localized string similar to To specify a setup for protected property {0}.{1}, use: mock.Setup<{2}>(x => x.{1}).Returns(value); mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one mock.SetupSet(x => x.{1}).Callback(callbackDelegate);. Looks up a localized string similar to The following setups were not matched: {0}. Allows setups to be specified for protected members by using their name as a string, rather than strong-typing them which is not possible due to their visibility. Specifies a setup for a void method invocation with the given , optionally specifying arguments for the method call. Name of the void method to be invoke. Optional arguments for the invocation. If argument matchers are used, remember to use rather than . Specifies a setup for an invocation 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. If argument matchers are used, remember to use rather than . Return type of the method or property. Specifies a setup for an invocation on a property getter with the given . Name of the property. Type of the property. Specifies a setup for an invocation on a property setter with the given . Name of the property. Type of the property. Allows the specification of a matching condition for an argument in a protected member setup, rather than a specific argument value. "ItExpr" refers to the argument being matched. Use this variant of argument matching instead of for protected setups. This class allows the setup to match a method invocation with an arbitrary value, with a value in a specified range, or even one that matches a given predicate, or null. Matches a null value of the given type. Required for protected mocks as the null value cannot be used directly as it prevents proper method overload selection. // Throws an exception for a call to Remove with a null string value. mock.Protected() .Setup("Remove", ItExpr.IsNull<string>()) .Throws(new InvalidOperationException()); Type of the value. 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() .Setup("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() .Setup("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() .Setup("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() .Setup("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() .Setup("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() .Setup("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase)) .Returns(1); Enables the Protected() method on , allowing setups 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 setups for the mock. Mocked object type. Typically omitted as it can be inferred from the mock instance. The mock to set the protected setups on. 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. Determines the way default values are generated calculated for loose mocks. Default behavior, which generates empty values for value types (i.e. default(int)), empty array and enumerables, and nulls for all other reference types. Whenever the default value generated by is null, replaces this value with a mock (if the type can be mocked). For sealed classes, a null value will be generated. Allows creation custom value matchers that can be used on setups and verification, completely replacing the built-in class with your own argument matching rules. Provided for the sole purpose of rendering the delegate passed to the matcher constructor if no friendly render lambda is provided. Allows creation custom value matchers that can be used on setups and verification, completely replacing the built-in class with your own argument matching rules. Type of the value to match. The argument matching is used to determine whether a concrete invocation in the mock matches a given setup. This matching mechanism is fully extensible. Creating a custom matcher is straightforward. You just need to create a method that returns a value from a call to with your matching condition and optional friendly render expression: public Order IsBigOrder() { return Match<Order>.Create( o => o.GrandTotal >= 5000, /* a friendly expression to render on failures */ () => IsBigOrder()); } This method can be used in any mock setup invocation: mock.Setup(m => m.Submit(IsBigOrder()).Throws<UnauthorizedAccessException>(); At runtime, Moq knows that the return value was a matcher and evaluates your predicate with the actual value passed into your predicate. Another example might be a case where you want to match a lists of orders that contains a particular one. You might create matcher like the following: public static class Orders { public static IEnumerable<Order> Contains(Order order) { return Match<IEnumerable<Order>>.Create(orders => orders.Contains(order)); } } 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.Setup(x => x.Save(Orders.Contains(order))) .Throws<ArgumentException>(); Initializes the match with the condition that will be checked in order to match invocation values. The condition to match against actual values. This method is used to set an expression as the last matcher invoked, which is used in the SetupSet to allow matchers in the prop = value delegate expression. This delegate is executed in "fluent" mode in order to capture the value being set, and construct the corresponding methodcall. This is also used in the MatcherFactory for each argument expression. This method ensures that when we execute the delegate, we also track the matcher that was invoked, so that when we create the methodcall we build the expression using it, rather than the null/default value returned from the actual invocation. Provides a mock implementation of . Any interface type can be used for mocking, but for classes, only abstract and virtual members can be mocked. The behavior of the mock with regards to the setups and the actual calls is determined by the optional that can be passed to the constructor. Type to mock, which can be an interface or a class. The following example shows establishing setups with specific values for method invocations: // Arrange var order = new Order(TALISKER, 50); var mock = new Mock<IWarehouse>(); mock.Setup(x => x.HasInventory(TALISKER, 50)).Returns(true); // Act order.Fill(mock.Object); // Assert Assert.True(order.IsFilled); The following example shows how to use the class to specify conditions for arguments instead of specific values: // Arrange var order = new Order(TALISKER, 50); var mock = new Mock<IWarehouse>(); // shows how to expect a value within a range mock.Setup(x => x.HasInventory( It.IsAny<string>(), It.IsInRange(0, 100, Range.Inclusive))) .Returns(false); // shows how to throw for unexpected calls. mock.Setup(x => x.Remove( It.IsAny<string>(), It.IsAny<int>())) .Throws(new InvalidOperationException()); // Act order.Fill(mock.Object); // Assert Assert.False(order.IsFilled); Ctor invoked by AsTInterface exclusively. Initializes an instance of the mock with default behavior. var mock = new Mock<IFormatProvider>(); 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 the specified behavior. var mock = new Mock<IFormatProvider>(MockBehavior.Relaxed); Behavior of the mock. 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. Returns the mocked object value. Specifies a setup on the mocked type for a call to to a void method. If more than one setup is specified 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.Setup(x => x.Execute("ping")); Specifies a setup 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 setup is specified for the same method or property, the latest one wins and is the one that will be executed. Lambda expression that specifies the method invocation. mock.Setup(x => x.HasInventory("Talisker", 50)).Returns(true); Specifies a setup on the mocked type for a call to to a property getter. If more than one setup 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 property getter. mock.SetupGet(x => x.Suspended) .Returns(true); Specifies a setup on the mocked type for a call to to a property setter. If more than one setup is set for the same property setter, the latest one wins and is the one that will be executed. This overloads allows the use of a callback already typed for the property type. Type of the property. Typically omitted as it can be inferred from the expression.Lambda expression that sets a property to a value. mock.SetupSet(x => x.Suspended = true); Specifies a setup on the mocked type for a call to to a property setter. If more than one setup is set for the same property setter, the latest one wins and is the one that will be executed. Lambda expression that sets a property to a value. mock.SetupSet(x => x.Suspended = true); Specifies that the given property should have "property behavior", meaning that setting its value will cause it to be saved and later returned when the property is requested. (this is also known as "stubbing"). Type of the property, inferred from the property expression (does not need to be specified). Property expression to stub. If you have an interface with an int property Value, you might stub it using the following straightforward call: var mock = new Mock<IHaveValue>(); mock.Stub(v => v.Value); After the Stub call has been issued, setting and retrieving the object value will behave as expected: IHaveValue v = mock.Object; v.Value = 5; Assert.Equal(5, v.Value); Specifies that the given property should have "property behavior", meaning that setting its value will cause it to be saved and later returned when the property is requested. This overload allows setting the initial value for the property. (this is also known as "stubbing"). Type of the property, inferred from the property expression (does not need to be specified). Property expression to stub.Initial value for the property. If you have an interface with an int property Value, you might stub it using the following straightforward call: var mock = new Mock<IHaveValue>(); mock.SetupProperty(v => v.Value, 5); After the SetupProperty call has been issued, setting and retrieving the object value will behave as expected: IHaveValue v = mock.Object; // Initial value was stored Assert.Equal(5, v.Value); // New value set which changes the initial value v.Value = 6; Assert.Equal(6, v.Value); Specifies that the all properties on the mock should have "property behavior", meaning that setting its value will cause it to be saved and later returned when the property is requested. (this is also known as "stubbing"). The default value for each property will be the one generated as specified by the property for the mock. If the mock is set to , the mocked default values will also get all properties setup recursively. 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 . The invocation was not call the times specified by . Expression to verify.The number of times a method is allowed to be called. Verifies that a specific invocation matching the given expression was performed on the mock, specifying a failure error message. 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.Message to show if verification fails. Verifies that a specific invocation matching the given expression was performed on the mock, specifying a failure error message. Use in conjuntion with the default . The invocation was not call the times specified by . Expression to verify.The number of times a method is allowed to be called.Message to show if verification fails. 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 specific invocation matching the given expression was performed on the mock. Use in conjuntion with the default . The invocation was not call the times specified by . Expression to verify.The number of times a method is allowed to be called.Type of return value from the expression. Verifies that a specific invocation matching the given expression was performed on the mock, specifying a failure error message. 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), "When filling orders, inventory has to be checked"); The invocation was not performed on the mock.Expression to verify.Message to show if verification fails.Type of return value from the expression. Verifies that a specific invocation matching the given expression was performed on the mock, specifying a failure error message. The invocation was not call the times specified by . Expression to verify.The number of times a method is allowed to be called.Message to show if verification fails.Type of return value from the expression. Verifies that a property was read on the mock. 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 was read on the mock. The invocation was not call the times specified by . The number of times a method is allowed to be called.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 was read on the mock, specifying a failure error message. 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.Message to show if verification fails. Type of the property to verify. Typically omitted as it can be inferred from the expression's return type. Verifies that a property was read on the mock, specifying a failure error message. The invocation was not call the times specified by . The number of times a method is allowed to be called.Expression to verify.Message to show if verification fails. Type of the property to verify. Typically omitted as it can be inferred from the expression's return type. Verifies that a property was set on the mock. This example assumes that the mock has been used, and later we want to verify that a given property was set on it: var mock = new Mock<IWarehouse>(); // exercise mock //... // Will throw if the test code didn't set the IsClosed property. mock.VerifySet(warehouse => warehouse.IsClosed = true); The invocation was not performed on the mock.Expression to verify. Verifies that a property was set on the mock. The invocation was not call the times specified by . The number of times a method is allowed to be called.Expression to verify. Verifies that a property was set on the mock, specifying a failure message. This example assumes that the mock has been used, and later we want to verify that a given property was set on it: var mock = new Mock<IWarehouse>(); // exercise mock //... // Will throw if the test code didn't set the IsClosed property. mock.VerifySet(warehouse => warehouse.IsClosed = true, "Warehouse should always be closed after the action"); The invocation was not performed on the mock.Expression to verify.Message to show if verification fails. Verifies that a property was set on the mock, specifying a failure message. The invocation was not call the times specified by . The number of times a method is allowed to be called.Expression to verify.Message to show if verification fails. Adds an interface implementation to the mock, allowing setups to be specified 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.Setup(x => x.Execute("ping")); // add IDisposable interface var disposable = mock.As<IDisposable>(); disposable.Setup(d => d.Dispose()).Verifiable(); Type of interface to cast the mock to. Raises the event referenced in using the given and arguments. The argument is invalid for the target event invocation, or the is not an event attach or detach expression. The following example shows how to raise a event: var mock = new Mock<IViewModel>(); mock.Raise(x => x.PropertyChanged -= null, new PropertyChangedEventArgs("Name")); 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 presenter = new OrdersPresenter(mockView.Object); // Check that the presenter has no selection by default Assert.Null(presenter.SelectedOrder); // Raise the event with a specific arguments data mockView.Raise(v => v.SelectionChanged += null, 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); Raises the event referenced in using the given and arguments for a non-EventHandler typed event. The arguments are invalid for the target event invocation, or the is not an event attach or detach expression. The following example shows how to raise a custom event that does not adhere to the standard EventHandler: var mock = new Mock<IViewModel>(); mock.Raise(x => x.MyEvent -= null, "Name", bool, 25); Obsolete. Obsolete. Obsolete. Obsolete. Obsolete. Exposes the mocked object instance. Provides legacy API members as extensions so that existing code continues to compile, but new code doesn't see then. Obsolete. Obsolete. Obsolete. Tracks the current mock and interception context. Having an active fluent mock context means that the invocation is being performed in "trial" mode, just to gather the target method and arguments that need to be matched later when the actual invocation is made. A that returns an empty default value for non-mockeable types, and mocks for all other types (interfaces and non-sealed classes) that can be mocked. 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. 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. Provides additional methods on mocks. Provided as extension methods as they confuse the compiler with the overloads taking Action. Specifies a setup on the mocked type for a call to to a property setter, regardless of its value. If more than one setup 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. Type of the mock. The target mock for the setup. Lambda expression that specifies the property setter. mock.SetupSet(x => x.Suspended); This method is not legacy, but must be on an extension method to avoid confusing the compiler with the new Action syntax. Verifies that a property has been set on the mock, regarless of its value. 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. The mock instance. Mocked type. 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, specifying a failure error message. 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. Message to show if verification fails. The mock instance. Mocked type. 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, regardless of the value but only the specified number of times. 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. The invocation was not call the times specified by . The mock instance. Mocked type. The number of times a method is allowed to be called. 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, regardless of the value but only the specified number of times, and specifying a failure error message. 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. The invocation was not call the times specified by . The mock instance. Mocked type. The number of times a method is allowed to be called. Message to show if verification fails. Expression to verify. Type of the property to verify. Typically omitted as it can be inferred from the expression's return type. Legacy Stub stuff, moved to the core API. Obsolete. Use . Obsolete. Use . Obsolete. Use . Defines the number of invocations allowed by a mocked method. Specifies that a mocked method should be invoked times as minimum. The minimun number of times. An object defining the allowed number of invocations. Specifies that a mocked method should be invoked one time as minimum. An object defining the allowed number of invocations. Specifies that a mocked method should be invoked time as maximun. The maximun number of times. An object defining the allowed number of invocations. Specifies that a mocked method should be invoked one time as maximun. An object defining the allowed number of invocations. Specifies that a mocked method should be invoked between and times. The minimun number of times. The maximun number of times. The kind of range. See . An object defining the allowed number of invocations. Specifies that a mocked method should be invoked exactly times. The times that a method or property can be called. An object defining the allowed number of invocations. Specifies that a mocked method should not be invoked. An object defining the allowed number of invocations. Specifies that a mocked method should be invoked exactly one time. An object defining the allowed number of invocations.