Moq is Mock you. The pronunciation can be read as Mock~you. It is a kind of Mock framework. Used for Mock testing in testing. Mock means simulation. Mock is a technique for mocking objects.
Test Method
// Prepare the Mock IFoo interfacevar mock = new Mock<IFoo>(); // Configure the method to prepare simulation. When calling the DoSomething method in the interface and passing the parameter "bing", return true(foo => ("ping")).Returns(true); // The out parameter is used in the method parameters// out arguments var outString = "ack"; // When the TryParse method is called, the out parameter returns "ack", the method returns true, lazy evaluated(foo => ("ping", out outString)).Returns(true); // ref parametervar instance = new Bar(); // Only when using ref call will the following test be matched(foo => (ref instance)).Returns(true); // When the method returns worth it, you can also access the returned value// Multiple parameters can be used here(x => (<string>())) .Returns((string s) => ()); // Throw an exception when called(foo => ("reset")).Throws<InvalidOperationException>(); (foo => ("")).Throws(new ArgumentException("command"); // The result returned by delay calculation(foo => ()).Returns(() => count); // Return a different value on each callvar mock = new Mock<IFoo>(); var calls = 0; (foo => ()) .Returns(() => calls) .Callback(() => calls++); // The first call returns 0, the next time is 1, and so on(());
Match parameters
// Any value(foo => (<string>())).Returns(true); // The provided value must match a function, lazy evaluated(foo => (<int>(i => i % 2 == 0))).Returns(true); // Match a range(foo => (<int>(0, 10, ))).Returns(true); // Match regular expressions(x => (("[a-d]+", ))).Returns("foo");
property
// Normal attributes(foo => ).Returns("bar"); // Multi-layer properties(foo => ).Returns("baz"); // The value of the expected setting property is "foo"(foo => = "foo"); // Or directly verify the assignment(foo => = "foo");
Set the property so that its value is automatically tracked
// Start the sets/gets of the "tracking" property(f => ); // Provide a default value(f => , "foo"); // Now, you can:IFoo foo = ; // Saved value("foo", ); // Reset a value = "bar"; ("bar", );
All properties can be prepared
();
event
// Throw an event(m => += null, new FooEventArgs(fooValue)); // Events in multi-layered descendants(m => += null, new FooEventArgs(fooValue)); // When the Submit method is called, an event is thrown(foo => ()).Raises(f => += null, ); // Throwing an exception will trigger the underlying behavior of the object// You may need to perform assertion processing later// Throw a custom eventpublic delegate void MyEventHandler(int i, bool b); public interface IFoo { event MyEventHandler MyEvent; } var mock = new Mock<IFoo>(); ... // Pass custom event parameters(foo => += null, 25, true);
Callback
var mock = new Mock<IFoo>(); (foo => ("ping")) .Returns(true) .Callback(() => calls++); // Use the parameters of the call(foo => (<string>())) .Returns(true) .Callback((string s) => (s)); // Use generic syntax(foo => (<string>())) .Returns(true) .Callback<string>(s => (s)); // Use multiple parameters(foo => (<int>(), <string>())) .Returns(true) .Callback<int, string>((i, s) => (s)); // Callbacks before and after calling(foo => ("ping")) .Callback(() => ("Before returns")) .Returns(true) .Callback(() => ("After returns"));
verify
(foo => ("ping")); // Provide custom error prompt information when verification fails(foo => ("ping"), "When doing operation X, the service should be pinged always"); // Method never called(foo => ("ping"), ()); // Called at least once(foo => ("ping"), ()); (foo => ); // Verify the assignment of attributes.(foo => ); // Verify that sets specific values for attributes(foo => ="foo"); // Verify matching parameters(foo => = (1, 5, ));
Customize Mock behavior
Mock's behavior is divided into strict Strict and loose Loose, which defaults to loose. In strict mode, using any behavior that is not specified will throw exceptions. In loose mode, no exceptions will be thrown, and the method will return the default value or an empty array, etc.
var mock = new Mock<IFoo>();
If the base class implementation is not overridden, the base class will not be called by default, which is required in the Mock Web/Html control.
var mock = new Mock<IFoo> { CallBase = true };
Creating an autorecursive Mock, the Mock object will return a new Mock object to any of its members.
var mock = new Mock<IFoo> { DefaultValue = }; // Default is// This property will now return a new Mock objectIBar value = ; // You can use the returned Mock object, and then access the attribute to return the same object instance// This allows us to perform subsequent settings// set further expectations on it if we want var barMock = (value); (b => ()).Returns(true);
Centralized Mock instance creation and management: You can create and validate all Mock objects using MockRepository in one place, setting MockBehavior, CallBse and DefaultValue constraints.
var factory = new MockFactory() { DefaultValue = }; // Create Mock objectvar fooMock = <IFoo>(); // Rewrite the settings of the repository when creatingvar barMock = <IBar>(); // Verify the object created through the repository();
other
// Used at the beginning of test casesusing () // Testingvar mock = new Mock<CommandBase>(); () .Setup<int>("Execute") .Returns(5); // If parameter matching is used, itExpr must be used instead of It// Future plans to improve() .Setup<string>("Execute", <string>()) .Returns(true);
Advanced Features
//Regain Mock object from Mock instanceIFoo foo = // get mock instance somehow var fooMock = (foo); (f => ()).Returns(true); // Implement multiple interfacesvar foo = new Mock<IFoo>(); var disposableFoo = <IDisposable>(); // Now IFoo mock has implemented the interface IDisposable :) (df => ());// Custom matching(foo => (IsLarge())).Throws<ArgumentException>(); ... public string IsLarge() { return Match<string>.Create(s => !(s) && > 100); }
The above is the commonly used method of moq introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!