Moq, is a mock you. The pronunciation can be read into mock~you. is one of the mock frames. Used for mock tests in tests. A mock is the meaning of impersonation. Mocks are a technique for simulating objects.
Test method
Prepare mock IFoo interface var Mock = new mock<ifoo> (); Configure the method to prepare for impersonation, returning a true mock when calling the DoSomething method in the interface and passing the argument "Bing". Setup (foo => foo. DoSomething ("ping")).
Returns (TRUE);
The parameter of the method uses the out parameter//out arguments var outstring = "ack"; When the TryParse method is invoked, the out parameter returns "ACK", and the method returns True, lazy evaluated mocks. Setup (foo => foo. TryParse ("Ping", out outstring)).
Returns (TRUE);
Ref parameter var instance = new Bar (); The following test mocks are matched only when called with ref. Setup (foo => foo. Submit (ref instance)).
Returns (TRUE); When the method returns, it is also possible to access the returned value//Here you can use multiple parameter mocks. Setup (x => x.dosomething (it.isany<string> ())).
Returns ((string s) => s.tolower ()); Throws an exception mock when invoked. Setup (foo => foo. DoSomething ("reset")).
Throws<invalidoperationexception> (); Mock. Setup (foo => foo. DoSomething ("")).
Throws (New ArgumentException ("command"); Deferred calculation returns a mock of the result. Setup (foo => foo. GetCount ()).
Returns (() => count);
At each call, a different value is returned var mock = new mock<ifoo> ();
var calls = 0; Mock. Setup (foo => foo. Getcountthing ()). Returns (() => calls).
Callback (() => calls++); The first call returns 0, the next one is 1, and so on Console.WriteLine (mocks). Object.getcountthing ());
Matching parameters
Any value
mocks. Setup (foo => foo. DoSomething (It.isany<string> ())). Returns (true);
The supplied value must match a function, lazy evaluated
mock. Setup (foo => foo. ADD (it.is<int> (i => i% 2 = 0))). Returns (true);
Matches a range
mock. Setup (foo => foo. ADD (it.isinrange<int> (0, range.inclusive)). Returns (true);
Matches a regular expression
mock. Setup (x => x.dosomething (It.isregex ("[a-d]+", Regexoptions.ignorecase)). Returns ("foo");
Property
Normal property
mocks. Setup (foo => foo. Name). Returns ("Bar");
Multi-layered property
mocks. Setup (foo => foo. Bar.Baz.Name). Returns ("Baz");
Expect the value of the Set property to be a "foo"
mock. Setupset foo => foo. Name = "foo");
or directly validate the assignment
mock. Verifyset foo => foo. Name = "foo");
Sets the property so that its value is tracked automatically
Starts the sets/gets mock of the tracking property
. Setupproperty (f => f.name);
Provides a default mock of values
. Setupproperty (f => f.name, "foo");
Now, you can:
IFoo foo = mock. Object;
Saved values
assert.equal ("foo", Foo. Name);
Reset a value of
foo. Name = "Bar";
Assert.equal ("Bar", Foo. Name);
You can also prepare all of the properties
Mock. Setupallproperties ();
Event
Throws an event
mock. Raise (M => m.fooevent + = null, new Fooeventargs (Foovalue));
An event mock in a multi-tiered descendant
. Raise (M => m.child.first.fooevent + = null, new Fooeventargs (Foovalue));
When the Submit method is invoked, an event mock is thrown
. Setup (foo => foo. Submit ()). Raises (f => f.sent + = null, eventargs.empty);
Throwing an exception triggers the behavior at the bottom of the object//
you may need to make an assertion process later/
/throw a custom event public
delegate void MyEventHandler (int i, bool b);
Public interface IFoo {event MyEventHandler myevent;}
var mock = new mock<ifoo> ();
...
Passes a custom event parameter
mock. Raise foo => foo. MyEvent + = null, true);
Callback
var mock = new mock<ifoo> ();
Mock. Setup (foo => foo. Execute ("ping"))
. Returns (True)
. Callback (() => calls++);
Mock with the parameters of the call
. Setup (foo => foo. Execute (It.isany<string> ()))
. Returns (True)
. Callback ((string s) => calls. ADD (s));
Use generic Syntax
mocks. Setup (foo => foo. Execute (It.isany<string> ()))
. Returns (True)
. Callback<string> (s => calls. ADD (s));
Mock with multiple parameters
. Setup (foo => foo. Execute (It.isany<int> (), it.isany<string> ())
. Returns (True)
. Callback<int, String> ((i, s) => calls. ADD (s));
Callback mocks before and after the call
. Setup (foo => foo. Execute ("ping"))
. Callback (() => Console.WriteLine ("Before Returns"))
. Returns (True)
. Callback (() => Console.WriteLine ("After Returns"));
Verify
Mock. Verify foo => foo. Execute ("ping"));
Provides a mock of custom error message information when validation fails
. Verify foo => foo. Execute ("ping"), "when doing operation X, the service should is pinged always");
Mocks from methods that are not invoked
. Verify foo => foo. Execute ("ping"), Times.never ());
At least one mock has been invoked
. Verify foo => foo. Execute ("ping"), times.atleastonce ());
Mock. Verifyget foo => foo. Name);
Validates an assignment to a property.
Mock. Verifyset foo => foo. Name);
Verify that the property is set to a specific value
mock. Verifyset foo => foo. Name = "foo");
Validates a matching parameter
mock. Verifyset foo => foo. Value = It.isinrange (1, 5, range.inclusive));
customizing Mock behavior
Mock behavior is divided into strict Strict and loose Loose, the default is loose. In strict mode, any behavior that is not specified will throw an exception, and in loose mode, no exception will be thrown, the default value or empty array can be returned, and so on.
var mocks = new mock<ifoo> (mockbehavior.strict);
If the implementation of the base class is not overridden, the base class will not be invoked by default, and it is necessary to Mock the web/html control.
var mock = new Mock<ifoo> {callbase = true};
To create an automatic recursive mock, the mock object will return a new mock object for any of its members.
var mock = new Mock<ifoo> {defaultvalue = Defaultvalue.mock};
The default is Defaultvalue.empty
//Now this property will return a new mock object
IBar value = mock. Object.bar;
The returned Mock object can be used, and then the access to the property returns the same object instance
//This allows us to perform subsequent settings
//Set further expectations on it if we want
var barm Ock = Mock.get (value);
Barmock.setup (b => b.submit ()). Returns (TRUE);
Centralized mock instance creation and management: You can use Mockrepository to create and validate all mock objects, set Mockbehavior, CALLBSE, and defaultvalue constraints in one place.
var factory = new Mockfactory (mockbehavior.strict) {defaultvalue = Defaultvalue.mock};
Create Mock object
var foomock = factory. Create<ifoo> ();
Rewrite the settings of the warehouse at the time of creation
var barmock = factory. Create<ibar> (mockbehavior.loose);
Validates object factory created through the warehouse
. Verify ();
Other
The
var mock = new mock<commandbase> () in the start of the test case using moq.protected ()///test, mocks. Protected ()
. Setup<int> ("Execute")
. Returns (5);
If you use a parameter match, you must use itexpr instead of It
//later to plan for improved
mocks. Protected ()
. Setup<string> ("Execute", Itexpr.isany<string> ())
. Returns (TRUE);
Advanced Features
Re-obtain mock objects from a mock instance
IFoo foo =//Get mock instance somehow
var foomock = Mock.get (foo);
Foomock.setup (f => f.submit ()). Returns (true);
Implement multiple interfaces
var foo = new mock<ifoo> ();
var disposablefoo = foo. As<idisposable> ();
Now the IFoo mock has implemented the interface IDisposable:) disposablefoo.setup (DF => DF. Dispose ());
Custom matching
mocks. Setup (foo => foo. Submit (IsLarge ())). Throws<argumentexception> (); ...
public string IsLarge ()
{return
match<string>. Create (S =>!) String.IsNullOrEmpty (s) && s.length >);
The above is a small set to introduce the common use of MOQ, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!