diff --git a/lib/Moq.dll b/lib/Moq.dll index abcb72ee6..7cab16290 100644 Binary files a/lib/Moq.dll and b/lib/Moq.dll differ diff --git a/lib/Moq.xml b/lib/Moq.xml index a29e2306a..54caa92d4 100644 --- a/lib/Moq.xml +++ b/lib/Moq.xml @@ -7,7 +7,7 @@ A that returns an empty default value - for invocations that do not have expectations or return values, with loose mocks. + for invocations that do not have setups or return values, with loose mocks. This is the default behavior for a mock. @@ -26,63 +26,15 @@ Optional arguments passed in to the call that requires a default value. - - Type to mock, which can be an interface or a class. + - Provides a mock implementation of . + Implements the fluent API. + + + + + Defines the Callback verb and overloads. - - Only abstract and virtual members of classes can be mocked. - - The behavior of the mock with regards to the expectations and the actual calls is determined - by the optional that can be passed to the - constructor. - - - - The following example shows setting expectations with specific values - for method invocations: - - //setup - data - var order = new Order(TALISKER, 50); - var mock = new Mock<IWarehouse>(); - - //setup - expectations - mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true); - - //exercise - order.Fill(mock.Object); - - //verify - Assert.True(order.IsFilled); - - The following example shows how to use the class - to specify conditions for arguments instead of specific values: - - //setup - data - var order = new Order(TALISKER, 50); - var mock = new Mock<IWarehouse>(); - - //setup - expectations - //shows how to expect a value within a range - mock.Expect(x => x.HasInventory( - It.IsAny<string>(), - It.IsInRange(0, 100, Range.Inclusive))) - .Returns(false); - - //shows how to throw for unexpected calls. contrast with the "verify" approach of other mock libraries. - mock.Expect(x => x.Remove( - It.IsAny<string>(), - It.IsAny<int>())) - .Throws(new InvalidOperationException()); - - //exercise - order.Fill(mock.Object); - - //verify - Assert.False(order.IsFilled); - - @@ -103,285 +55,17 @@ - - - Adds an interface implementation to the mock, - allowing expectations to be set for it. - - - This method can only be called before the first use - of the mock property, at which - point the runtime type has already been generated - and no more interfaces can be added to it. - - Also, must be an - interface and not a class, which must be specified - when creating the mock instead. - - - The mock type - has already been generated by accessing the property. - The specified - is not an interface. - - The following example creates a mock for the main interface - and later adds to it to verify - it's called by the consumer code: - - var mock = new Mock<IProcessor>(); - mock.Expect(x => x.Execute("ping")); - - // add IDisposable interface - var disposable = mock.As<IDisposable>(); - disposable.Expect(d => d.Dispose()).Verifiable(); - - - Type of interface to cast the mock to. - - - - Sets an expectation on the mocked type for a call to - to a value returning method. - - Type of the return value. Typically omitted as it can be inferred from the expression. - - If more than one expectation is set for the same method or property, - the latest one wins and is the one that will be executed. - - Lambda expression that specifies the expected method invocation. - - - mock.Expect(x => x.HasInventory("Talisker", 50)).Returns(true); - - - - - - Sets an expectation on the mocked type for a call to - to a void method. - - - If more than one expectation is set for the same method or property, - the latest one wins and is the one that will be executed. - - Lambda expression that specifies the expected method invocation. - - - var mock = new Mock<IProcessor>(); - mock.Expect(x => x.Execute("ping")); - - - - - - Sets an expectation on the mocked type for a call to - to a property getter. - - - If more than one expectation is set for the same property getter, - the latest one wins and is the one that will be executed. - - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property getter. - - - mock.ExpectGet(x => x.Suspended) - .Returns(true); - - - - - - Sets an expectation on the mocked type for a call to - to a property setter. - - - If more than one expectation is set for the same property setter, - the latest one wins and is the one that will be executed. - - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property setter. - - - mock.ExpectSet(x => x.Suspended); - - - - - - Sets an expectation on the mocked type for a call to - to a property setter with a specific value. - - - More than one expectation can be set for the setter with - different values. - - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property setter. - The value expected to be set for the property. - - - mock.ExpectSet(x => x.Suspended, true); - - - - - - Implements . - - - - - Implements . - - - - - Verifies that a specific invocation matching the given - expression was performed on the mock. Use in conjuntion - with the default . - - - This example assumes that the mock has been used, - and later we want to verify that a given invocation - with specific parameters was performed: - - var mock = new Mock<IProcessor>(); - // exercise mock - //... - // Will throw if the test code didn't call Execute with a "ping" string argument. - mock.Verify(proc => proc.Execute("ping")); - - - The invocation was not performed on the mock. - Expression to verify. - - - - Verifies that a specific invocation matching the given - expression was performed on the mock. Use in conjuntion - with the default . - - - This example assumes that the mock has been used, - and later we want to verify that a given invocation - with specific parameters was performed: - - var mock = new Mock<IWarehouse>(); - // exercise mock - //... - // Will throw if the test code didn't call HasInventory. - mock.Verify(warehouse => warehouse.HasInventory(TALISKER, 50)); - - - The invocation was not performed on the mock. - Expression to verify. - Type of return value from the expression. - - - - Verifies that a property was read on the mock. - Use in conjuntion with the default . - - - This example assumes that the mock has been used, - and later we want to verify that a given property - was retrieved from it: - - var mock = new Mock<IWarehouse>(); - // exercise mock - //... - // Will throw if the test code didn't retrieve the IsClosed property. - mock.VerifyGet(warehouse => warehouse.IsClosed); - - - The invocation was not performed on the mock. - Expression to verify. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. - - - - Verifies that a property has been set on the mock. - Use in conjuntion with the default . - - - This example assumes that the mock has been used, - and later we want to verify that a given invocation - with specific parameters was performed: - - var mock = new Mock<IWarehouse>(); - // exercise mock - //... - // Will throw if the test code didn't set the IsClosed property. - mock.VerifySet(warehouse => warehouse.IsClosed); - - - The invocation was not performed on the mock. - Expression to verify. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. - - - - Verifies that a property has been set on the mock to the given value. - Use in conjuntion with the default . - - - This example assumes that the mock has been used, - and later we want to verify that a given invocation - with specific parameters was performed: - - var mock = new Mock<IWarehouse>(); - // exercise mock - //... - // Will throw if the test code didn't set the IsClosed property to true - mock.VerifySet(warehouse => warehouse.IsClosed, true); - - - The invocation was not performed on the mock. - Expression to verify. - The value that should have been set on the property. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. - - - - Exposes the mocked object instance. - - - - - Specifies the behavior to use when returning default values for - unexpected invocations. - - - - - Behavior of the mock, according to the value set in the constructor. - - - - - Implements the fluent API. - - - - - Defines the Callback verb and overloads. - - Specifies a callback to invoke when the method is called. - Callback method to invoke. + 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()) + mock.Setup(x => x.Execute()) .Callback(() => called = true); @@ -392,7 +76,7 @@ arguments. Argument type of the invoked method. - Callback method to invoke. + Callback method to invoke. Invokes the given callback with the concrete invocation argument value. @@ -400,7 +84,7 @@ it as part of the lambda expression for the callback: - mock.Expect(x => x.Execute(It.IsAny<string>())) + mock.Setup(x => x.Execute(It.IsAny<string>())) .Callback((string command) => Console.WriteLine(command)); @@ -412,7 +96,7 @@ Type of the first argument of the invoked method. Type of the second argument of the invoked method. - Callback method to invoke. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -420,7 +104,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>())) .Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2)); @@ -435,7 +119,7 @@ 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. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -443,7 +127,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>())) @@ -460,7 +144,7 @@ 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. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -468,7 +152,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), @@ -479,7 +163,7 @@ - Defines occurrence members to constraint expectations. + Defines occurrence members to constraint setups. @@ -489,7 +173,7 @@ var mock = new Mock<ICommand>(); - mock.Expect(foo => foo.Execute("ping")) + mock.Setup(foo => foo.Execute("ping")) .AtMostOnce(); @@ -498,34 +182,106 @@ The expected invocation can happen at most specified number of times. + The number of times to accept calls. var mock = new Mock<ICommand>(); - mock.Expect(foo => foo.Execute("ping")) + mock.Setup(foo => foo.Execute("ping")) .AtMost( 5 ); - + - Defines the Verifiable verb. + Defines the Raises verb. - + - Marks the expectation as verifiable, meaning that a call - to will check if this particular - expectation was met. + 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 marks the expectation as verifiable: + The following example shows how to raise an event when + the setup is met: - mock.Expect(x => x.Execute("ping")) - .Returns(true) - .Verifiable(); + 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. @@ -534,23 +290,23 @@ Specifies the mocked event that will be raised - when the expectation is met. + 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 set an expectation that will - raise an event when it's met: + 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; - // set the expectation and the handler to raise - mock.Expect(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) + // setup the invocation and the handler to raise + mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) .Raises(handler, EventArgs.Empty); @@ -558,7 +314,7 @@ Specifies the mocked event that will be raised - when the expectation is met. + when the setup is matched. The mocked event, retrieved from or . @@ -570,7 +326,7 @@ Specifies the mocked event that will be raised - when the expectation is met. + when the setup is matched. The mocked event, retrieved from or . @@ -583,7 +339,7 @@ Specifies the mocked event that will be raised - when the expectation is met. + when the setup is matched. The mocked event, retrieved from or . @@ -597,7 +353,7 @@ Specifies the mocked event that will be raised - when the expectation is met. + when the setup is matched. The mocked event, retrieved from or . @@ -612,7 +368,7 @@ Specifies the mocked event that will be raised - when the expectation is met. + when the setup is matched. The mocked event, retrieved from or . @@ -625,6 +381,41 @@ 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 @@ -632,9 +423,14 @@ 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 expectation. This + 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. @@ -665,7 +461,7 @@ var order = new Order { ... }; var mock = new Mock<IRepository<Order>>(); - mock.Expect(x => x.Save(Orders.Contains(order))) + mock.Setup(x => x.Save(Orders.Contains(order))) .Throws<ArgumentException>(); Note that the return value from the compiler matcher is irrelevant. @@ -691,11 +487,11 @@ At runtime, the mocked method will be invoked with a specific list of orders. This value will be passed to this runtime matcher as the first argument, while the second argument is the - one specified in the expectation (x.Save(Orders.Contains(order))). + 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 expectation is verified. + the setup matches and is evaluated. @@ -728,7 +524,7 @@ var order = new Order { ... }; var mock = new Mock<IRepository<Order>>(); - mock.Expect(x => x.Save(Orders.Contains(order))) + mock.Setup(x => x.Save(Orders.Contains(order))) .Throws<ArgumentException>(); // use mock, invoke Save, and have the matcher filter. @@ -1060,18 +856,36 @@ The argument value to check. The name of the argument. - + - Defines the Returns verb for property get expectations. + Checks an argument to ensure it is in the specified range including the edges. - Type of the property. + 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. - + - Base interface for . + 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. @@ -1079,12 +893,12 @@ Return a true value from the property getter call: - mock.ExpectGet(x => x.Suspended) + mock.SetupGet(x => x.Suspended) .Returns(true); - + Specifies a function that will calculate the value to return for the property. @@ -1092,7 +906,7 @@ Return a calculated value when the property is retrieved: - mock.ExpectGet(x => x.Suspended) + mock.SetupGet(x => x.Suspended) .Returns(() => returnValues[0]); The lambda expression to retrieve the return value is lazy-executed, @@ -1101,22 +915,23 @@ that moment. - + - Defines the Callback verb for property getter expectations. + 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. + Callback method to invoke. Invokes the given callback with the property value being set. - mock.ExpectGet(x => x.Suspended) + mock.SetupGet(x => x.Suspended) .Callback(() => called = true) .Returns(true); @@ -1127,18 +942,19 @@ 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. @@ -1146,12 +962,12 @@ Return a true value from the method call: - mock.Expect(x => x.Execute("ping")) + mock.Setup(x => x.Execute("ping")) .Returns(true); - + Specifies a function that will calculate the value to return from the method. @@ -1159,7 +975,7 @@ Return a calculated value when the method is called: - mock.Expect(x => x.Execute("ping")) + mock.Setup(x => x.Execute("ping")) .Returns(() => returnValues[0]); The lambda expression to retrieve the return value is lazy-executed, @@ -1168,7 +984,7 @@ that moment. - + Specifies a function that will calculate the value to return from the method, retrieving the arguments for the invocation. @@ -1178,18 +994,18 @@ Return a calculated value which is evaluated lazily at the time of the invocation. - The lookup list can change between invocations and the expectation + 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.Expect(x => x.Execute(It.IsAny<string>())) + 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. @@ -1205,14 +1021,14 @@ expression: - mock.Expect(x => x.Execute( + 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. @@ -1229,7 +1045,7 @@ expression: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>())) @@ -1237,7 +1053,7 @@ - + Specifies a function that will calculate the value to return from the method, retrieving the arguments for the invocation. @@ -1255,7 +1071,7 @@ expression: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), @@ -1278,7 +1094,7 @@ This example shows how to throw an exception when the method is invoked with an empty string argument: - mock.Expect(x => x.Execute("")) + mock.Setup(x => x.Execute("")) .Throws(new ArgumentException()); @@ -1287,17 +1103,17 @@ Specifies the type of exception to throw when the method is invoked. - Type of exception to instantiate and throw when the expectation is met. + 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.Expect(x => x.Execute("")) + mock.Setup(x => x.Execute("")) .Throws<ArgumentException>(); - + Implements the fluent API. @@ -1307,24 +1123,25 @@ Implements the fluent API. - + Defines the Callback verb and overloads for callbacks on - expectations that return a value. + setups that return a value. - Type of the return value of the expectation. + Mocked type. + Type of the return value of the setup. - + Specifies a callback to invoke when the method is called. - Callback method to invoke. + 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()) + mock.Setup(x => x.Execute()) .Callback(() => called = true) .Returns(true); @@ -1332,13 +1149,13 @@ 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. + Callback method to invoke. Invokes the given callback with the concrete invocation argument value. @@ -1346,20 +1163,20 @@ it as part of the lambda expression for the callback: - mock.Expect(x => x.Execute(It.IsAny<string>())) + 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. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -1367,7 +1184,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>())) .Callback((string arg1, string arg2) => Console.WriteLine(arg1 + arg2)) @@ -1375,7 +1192,7 @@ - + Specifies a callback to invoke when the method is called that receives the original arguments. @@ -1383,7 +1200,7 @@ 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. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -1391,7 +1208,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>())) @@ -1400,7 +1217,7 @@ - + Specifies a callback to invoke when the method is called that receives the original arguments. @@ -1409,7 +1226,7 @@ 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. + Callback method to invoke. Invokes the given callback with the concrete invocation arguments values. @@ -1417,7 +1234,7 @@ them as part of the lambda expression for the callback: - mock.Expect(x => x.Execute( + mock.Setup(x => x.Execute( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), @@ -1465,7 +1282,7 @@ The type to find immediate ancestors of - + Implements the fluent API. @@ -1482,7 +1299,7 @@ var mock = new Mock<ICommand>(); - mock.Expect(foo => foo.Execute("ping")) + mock.Setup(foo => foo.Execute("ping")) .Never(); @@ -1492,147 +1309,129 @@ with unexpected invocations. - + Implements the fluent API. - + Implements the fluent API. - + Implements the fluent API. - Defines the Callback verb for property setter expectations. + 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.ExpectSet(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 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. + property value being set. - - Typically used when the actual argument value for a method - call is not relevant. - + Callback method to invoke. + Invokes the given callback with the property value being set. - // Throws an exception for a call to Remove with any string value. - mock.Expect(x => x.Remove(It.IsAny<string>())).Throws(new InvalidOperationException()); + mock.SetupSet(x => x.Suspended) + .Callback((bool state) => Console.WriteLine(state)); - Type of the value. + + + + 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.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 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.Expect(x => x.HasInventory( - It.IsAny<string>(), - It.IsInRange(0, 100, Range.Inclusive))) - .Returns(false); - - + 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.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 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.Expect(x => x.Check(It.IsRegex("[a-z]+", RegexOptions.IgnoreCase))).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.Expect(x => x.StringMethod(A.MagicString())); + mock.Setup(x => x.StringMethod(A.MagicString())); pbulic static class A { @@ -1657,185 +1456,79 @@ - Base class for mocks and static helper class with methods that - apply to mocked objects, such as to - retrieve a from an object instance. - - - - - Base mock interface exposing non-generic members. - - - - - Creates a handler that can be associated to an event receiving - the given and can be used - to raise the event. - - Type of - data passed in to the event. - - This example shows how to invoke an event with a custom event arguments - class in a view that will cause its corresponding presenter to - react by changing its state: - - var mockView = new Mock<IOrdersView>(); - var mockedEvent = mockView.CreateEventHandler<OrderEventArgs>(); - - var presenter = new OrdersPresenter(mockView.Object); - - // Check that the presenter has no selection by default - Assert.Null(presenter.SelectedOrder); - - // Create a mock event handler of the appropriate type - var handler = mockView.CreateEventHandler<OrderEventArgs>(); - // Associate it with the event we want to raise - mockView.Object.Cancel += handler; - // Finally raise the event with a specific arguments data - handler.Raise(new OrderEventArgs { Order = new Order("moq", 500) }); - - // Now the presenter reacted to the event, and we have a selected order - Assert.NotNull(presenter.SelectedOrder); - Assert.Equal("moq", presenter.SelectedOrder.ProductName); - - - - - - Creates a handler that can be associated to an event receiving - a generic and can be used - to raise the event. - - - This example shows how to invoke a generic event in a view that will - cause its corresponding presenter to react by changing its state: - - var mockView = new Mock<IOrdersView>(); - var mockedEvent = mockView.CreateEventHandler(); - - var presenter = new OrdersPresenter(mockView.Object); - - // Check that the presenter is not in the "Canceled" state - Assert.False(presenter.IsCanceled); - - // Create a mock event handler of the appropriate type - var handler = mockView.CreateEventHandler(); - // Associate it with the event we want to raise - mockView.Object.Cancel += handler; - // Finally raise the event - handler.Raise(EventArgs.Empty); - - // Now the presenter reacted to the event, and changed its state - Assert.True(presenter.IsCanceled); - - - - - - Verifies that all verifiable expectations have been met. - - - This example sets up an expectation and marks it as verifiable. After - the mock is used, a call is issued on the mock - to ensure the method in the expectation was invoked: - - var mock = new Mock<IWarehouse>(); - mock.Expect(x => x.HasInventory(TALISKER, 50)).Verifiable().Returns(true); - ... - // other test code - ... - // Will throw if the test code has didn't call HasInventory. - mock.Verify(); - - - Not all verifiable expectations were met. - - - - Verifies all expectations regardless of whether they have - been flagged as verifiable. - - - This example sets up an expectation without marking it as verifiable. After - the mock is used, a call is issued on the mock - to ensure that all expectations are met: - - var mock = new Mock<IWarehouse>(); - mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true); - ... - // other test code - ... - // Will throw if the test code has didn't call HasInventory, even - // that expectation was not marked as verifiable. - mock.VerifyAll(); - - - At least one expectation was not met. - - - - Whether the base member virtual implementation will be called - for mocked classes if no expectation is met. Defaults to . - - - - - Determines how to generate default values for loose mocks on - unexpected invocations. - - - - - The mocked object instance. - + 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 expectation to an object - instance which is not the original but rather - the object associated with it: - - // Typed instance, not the mock, is retrieved from some test API. - HttpContextBase context = GetMockContext(); - - // context.Request is the typed object from the "real" API - // so in order to add an expectation to it, we need to get - // the mock that "owns" it - Mock<HttpRequestBase> request = Mock.Get(context.Request); - mock.Expect(req => req.AppRelativeCurrentExecutionFilePath) - .Returns(tempUrl); - - - - - - Initializes the mock - + 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. - + Returns the mocked object value. + - Implements . - + 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. - Implements . - + 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. @@ -1845,59 +1538,137 @@ - Implements . - - Type of event argument class. + 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); + + - Implements - + 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. - - - - - Exposes the list of extra interfaces implemented by the mock. - + Base class for mocks and static helper class with methods that + apply to mocked objects, such as to + retrieve a from an object instance. + - Implements . - + Behavior of the mock, according to the value set in the constructor. + - Implements . - + Whether the base member virtual implementation will be called + for mocked classes if no setup is matched. Defaults to . + - Implements . + 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 expectations and need to return a default + have no setups and need to return a default value (for loose mocks). - + - The mocked object instance. Implements . + Exposes the list of extra interfaces implemented by the mock. - + - Retrieves the type of the mocked object, its generic type argument. - This is used in the auto-mocking of hierarchy access. + 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 . @@ -1919,6 +1690,12 @@ event argument data. + + + Raises the associated event with the given + event argument data. + + Provides support for attaching a to @@ -1931,33 +1708,9 @@ Event raised whenever the mocked event is rised. - - - Options to customize the behavior of the mock. - - - - - Causes the mock to always throw - an exception for invocations that don't have a - corresponding expectation. - - - - - Will never throw exceptions, returning default - values when necessary (null for reference types, - zero for value types or empty enumerables and arrays). - - - - - Default mock behavior, which equals . - - - Exception thrown by mocks when expectations are not met, + Exception thrown by mocks when setups are not matched, the mock is not properly setup, etc. @@ -2034,44 +1787,44 @@ 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()); + // 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 expectations are already checked + // 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 expectation will also throw a MockException. + // 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 expectations: + 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 expectation will be verified at the end of the "using" block - foo.Expect(f => f.Do()).Verifiable(); + // this setup will be verified when we verify the factory + foo.Setup(f => f.Do()).Verifiable(); - // this expectation will NOT be verified - foo.Expect(f => f.Calculate()); + // this setup will NOT be verified + foo.Setup(f => f.Calculate()); - // this expectation will be verified at the end of the "using" block - bar.Expect(b => b.Redo()).Verifiable(); + // 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 - // expectations exist will NOT throw exceptions, + // setups exist will NOT throw exceptions, // and will rather return default values. factory.Verify(); - // At this point verifiable expectations are already checked + // 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 @@ -2084,7 +1837,7 @@ var foo = factory.Create<IFoo>(MockBehavior.Loose); var bar = factory.Create<IBar>(); - // set expectations + // specify setups // exercise the mocks here @@ -2202,7 +1955,7 @@ Verifies all verifiable expectations on all mocks created by this factory. - + One or more mocks had expectations that were not satisfied. @@ -2210,10 +1963,10 @@ 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 @@ -2226,7 +1979,7 @@ Whether the base member virtual implementation will be called - for mocked classes if no expectation is met. Defaults to . + for mocked classes if no setup is matched. Defaults to . @@ -2262,6 +2015,11 @@ 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.. @@ -2282,32 +2040,6 @@ Looks up a localized string similar to A matching constructor for the given arguments was not found on the mocked type.. - - - Looks up a localized string similar to Invalid expectation on a non-overridable member: - {0}. - - - - - Looks up a localized string similar to A lambda expression is expected as the argument to It.Is<T>.. - - - - - Looks up a localized string similar to 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 {0} involves a field access, which is not supported. Use properties instead.. @@ -2333,7 +2065,7 @@ Looks up a localized string similar to Method {0}.{1} is public. Use strong-typed Expect overload instead: - mock.Expect(x => x.{1}()); + mock.Setup(x => x.{1}()); . @@ -2343,24 +2075,73 @@ {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 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 All invocations on the mock must have a corresponding expectation.. - + + + 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 The given invocation was not performed on the mock.. + Looks up a localized string similar to All invocations on the mock must have a corresponding setup.. @@ -2390,15 +2171,56 @@ - Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding expectation that provides it.. + Looks up a localized string similar to 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 set expectations for public property {0}.{1}, use the typed overloads, such as: - mock.Expect(x => x.{1}).Returns(value); - mock.ExpectGet(x => x.{1}).Returns(value); //equivalent to previous one - mock.ExpectSet(x => x.{1}).Callback(callbackDelegate); + Looks up a localized string similar to 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); . @@ -2409,7 +2231,7 @@ - Looks up a localized string similar to Only property accesses are supported in intermediate invocations on an expectation. Unsupported expression {0}.. + Looks up a localized string similar to Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}.. @@ -2417,62 +2239,74 @@ 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 set expectations for protected property {0}.{1}, use: - mock.Expect<{2}>(x => x.{1}).Returns(value); - mock.ExpectGet(x => x.{1}).Returns(value); //equivalent to previous one - mock.ExpectSet(x => x.{1}).Callback(callbackDelegate);. + Looks up a localized string similar to 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 expectations were not met: + Looks up a localized string similar to The following setups were not matched: {0}. - + - Allows expectations to be set for protected members by using their + 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. - + - Sets an expectation on the void method with the given + 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. + Optional arguments for the invocation. If argument matchers are used, + remember to use rather than . - + - Sets an expectation on a property or a non void method with the given + 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. + Optional arguments for the invocation. If argument matchers are used, + remember to use rather than . Return type of the method or property. - + - Sets an expectation on a property getter with the given + Specifies a setup for an invocation on a property getter with the given . Name of the property. Type of the property. - + - Sets an expectation on a property setter with the given + Specifies a setup for an invocation on a property setter with the given . Name of the property. @@ -2481,16 +2315,34 @@ Allows the specification of a matching condition for an - argument in a protected member expectation, rather than a specific + 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 expectations. - This class allows the expectation to match a method invocation + 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. + 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. @@ -2504,7 +2356,7 @@ // Throws an exception for a call to Remove with any string value. mock.Protected() - .Expect("Remove", ItExpr.IsAny<string>()) + .Setup("Remove", ItExpr.IsAny<string>()) .Throws(new InvalidOperationException()); @@ -2525,14 +2377,14 @@ Do method is an even number. mock.Protected() - .Expect("Do", ItExpr.Is<int>(i => i % 2 == 0)) + .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() - .Expect("GetUser", ItExpr.Is<int>(i => i < 0)) + .Setup("GetUser", ItExpr.Is<int>(i => i < 0)) .Throws(new ArgumentException()); @@ -2550,7 +2402,7 @@ with an integer argument within the 0..100 range. mock.Protected() - .Expect("HasInventory", + .Setup("HasInventory", ItExpr.IsAny<string>(), ItExpr.IsInRange(0, 100, Range.Inclusive)) .Returns(false); @@ -2567,7 +2419,7 @@ string argument matches the given regular expression: mock.Protected() - .Expect("Check", ItExpr.IsRegex("[a-z]+")) + .Setup("Check", ItExpr.IsRegex("[a-z]+")) .Returns(1); @@ -2583,7 +2435,7 @@ string argument matches the given regular expression, in a case insensitive way: mock.Protected() - .Expect("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase)) + .Setup("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase)) .Returns(1); @@ -2591,23 +2443,23 @@ Enables the Protected() method on , - allowing expectations to be set for protected members by using their + 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 expectations for the mock. + 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 expectations on. + The mock to set the protected setups on. - + - + @@ -2652,156 +2504,707 @@ For sealed classes, a null value will be generated. - + - Core implementation of the interface. - - - Type to mock. + 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. + + + - Initializes an instance of the mock with default behavior and with - the given constructor arguments for the class. (Only valid when is a class) + 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. - - The mock will try to find the best match constructor given the constructor arguments, and invoke that - to initialize the instance. This applies only for classes, not interfaces. - - - var mock = new Mock<MyProvider>(someArgument, 25); - - Optional constructor arguments if the mocked type is a class. - Initializes an instance of the mock with default behavior. - - - var mock = new Mock<IFormatProvider>(); - + Initializes an instance of the mock with 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 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. + 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); + + + - Implements . + Obsolete. - Lambda expression that specifies the expected method invocation. - Implements . + Obsolete. - Type of the return value. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected method invocation. - Implements . + Obsolete. - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property getter. - Implements . + Obsolete. - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property setter. - Implements . - - Type of the property. Typically omitted as it can be inferred from the expression. - Lambda expression that specifies the expected property setter. - The value expected to be set for the property. - - - - Implements . + Obsolete. - Expression to verify. - - - - Implements . - - Expression to verify. - Type of return value from the expression. - + - Implements . - - Expression to verify. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. + Exposes the mocked object instance. + - + - Implements . + Provides legacy API members as extensions so that + existing code continues to compile, but new code + doesn't see then. - Expression to verify. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. - + - Implements . + Obsolete. - Expression to verify. - The value that should have been set on the property. - Type of the property to verify. Typically omitted as it can - be inferred from the expression's return type. - + - Implements . + Obsolete. - + - Implements . + Obsolete. - + - Implements . + Tracks the current mock and interception context. - Type of interface to cast the mock to. - + - Exposes the mocked object instance. + 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. @@ -2844,87 +3247,221 @@ corresponding EventInfo for it. - + - Adds Stub extension method to a mock so that you can - stub properties. + Provides additional methods on mocks. + + Provided as extension methods as they confuse the compiler + with the overloads taking Action. + - + - Specifies that the given property should have stub behavior, - meaning that setting its value will cause it to be saved and - later returned when the property is requested. + Specifies a setup on the mocked type for a call to + to a property setter, regardless of its value. - Mocked type, inferred from the object - where this method is being applied (does not need to be specified). - Type of the property, inferred from the property - expression (does not need to be specified). - The instance to stub. - Property expression to stub. - - If you have an interface with an int property Value, you might - stub it using the following straightforward call: + + 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. + - var mock = new Mock<IHaveValue>(); - mock.Stub(v => v.Value); + mock.SetupSet(x => x.Suspended); - After the Stub call has been issued, setting and - retrieving the object value will behave as expected: + + + 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: - IHaveValue v = mock.Object; - - v.Value = 5; - Assert.Equal(5, v.Value); + 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. - + - Specifies that the given property should have stub 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. - - Mocked type, inferred from the object - where this method is being applied (does not need to be specified). - Type of the property, inferred from the property - expression (does not need to be specified). - The instance to stub. - 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: + 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<IHaveValue>(); - mock.Stub(v => v.Value, 5); + var mock = new Mock<IWarehouse>(); + // exercise mock + //... + // Will throw if the test code didn't set the IsClosed property. + mock.VerifySet(warehouse => warehouse.IsClosed); - After the Stub call has been issued, setting and - retrieving the object value will behave as expected: + + 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: - 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); + 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 . + - Stubs all properties on the mock, setting the default value to - the one generated as specified by the - property. + Obsolete. Use . - Mocked type, typically omitted as it can be inferred from the mock argument. - The mock to stub. - - If the mock is set to , - the mocked default values will also be stubbed recursively. - + + + + 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.