Moq 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.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)); Defines the Callback verb and overloads for callbacks on expectations that return a value. 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. Defines the Returns verb. Base interface for . 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); 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()); 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(); 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 Invocation on abstract mock member must have a corresponding expectation.. 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 Field calls are not supported. Use interfaces and properties instead.. Looks up a localized string similar to Invocation on interface member must have a corresponding expectation.. 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 {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 Object instance was not created by Moq.. Looks up a localized string similar to Property {0}.{1} is write-only.. Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding expectation.. Looks up a localized string similar to Expression {0} is not supported.. Looks up a localized string similar to The following expectations were not met: {0}. 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. Supports the serialization infrastructure. 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. Implements the fluent API. Implements the fluent API. 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(); Implements the fluent API. Implements the actual interception and method invocation for all mocks, even MBROs (via the . 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. Utility factory class to use to construct multiple mocks when consistent behavior and verification is desired for all of them. If multiple mocks will be created during a test, passing the desired (if different than the ) 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 the exact same and posterior verification. The following is a straightforward example on how to create and automatically verify strict mocks: 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. Initializes the factory with the given for newly created mocks from the factory. The behavior to use for mocks created using the factory method Creates a new mock with the specified at factory construction time. Type to mock. A new . using (var factory = new MockFactory(MockBehavior.Relaxed, MockVerification.Verifiable)) { var foo = factory.Create<IFoo>(); // use mock on tests } Creates a new mock with the 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. A new . using (var factory = new MockFactory(MockBehavior.Default, MockVerification.Verifiable)) { var mock = factory.Create<MyBase>("Foo", 25, true); // use mock on tests } 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. 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. Matches the behavior of classes and interfaces in equivalent manual mocks: abstract methods need to have an expectation (override), as well as all interface members. Other members (virtual and non-virtual) can be called freely and will end up invoking the implementation on the target type if available. Will only throw exceptions for abstract methods and interface members which need to return a value and don't have a corresponding expectation. Will never throw exceptions, returning default values when necessary (null for reference types or zero for value types). Default mock behavior, which equals . Provides a mock implementation of . If the mocked is a (such as a Windows Forms control or another -derived class) all members will be mockeable, even if they are not virtual or abstract. For regular .NET classes ("POCOs" or Plain Old CLR Objects), only abstract and virtual members 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.IsTrue(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.IsFalse(order.IsFilled); Internal interface implemented by Mock{T} to enable to verify mocks in a generic way. 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. Note: For a derived class, any calls done in the constructor itself (i.e. calls to private members, initialization methods, etc. invoked from the constructor) will not go through the proxied mock and will instead be direct invocations in the underlying object. This is a known limitation. var mock = new Mock<MyProvider>(someArgument, 25); 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. Note: For a derived class, any calls done in the constructor itself will not go through the proxied mock and will instead be direct invocations in the underlying object. This is known limitation. var mock = new Mock<MyProvider>(someArgument, 25); 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); 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 value returning 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. mock.Expect(x => x.HasInventory("Talisker", 50)).Returns(true); 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. Provides a mock implementation of . If the mocked is a (such as a Windows Forms control or another -derived class) all members will be mockeable, even if they are not virtual or abstract. For regular .NET classes ("POCOs" or Plain Old CLR Objects), only abstract and virtual members 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.IsTrue(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.IsFalse(order.IsFilled); Exposes the mocked object instance. Used for testing the mock factory. Static 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 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 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's managing them Mock<HttpRequestBase> request = Mock.Get(context.Request); mock.Expect(req => req.AppRelativeCurrentExecutionFilePath) .Returns(tempUrl); 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()); 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); Implemented by all generated mock object instances. Reference the Mock that contains this as the mock.Object value. Adapter for Remoting interception. It allows invocation of the underlying proxied object if a given member is not abstract on the target type. We use a null interceptor for the generated class as we'll be already intercepting through remoting, which is more powerful and gives us additional interception points (private members, non-virtuals, etc.). 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) 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. Performs bottom-up analysis to determine which nodes can possibly be part of an evaluated sub-tree. TODO: remove this code when https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=331583 is fixed. 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.