Common usage of moq of Recommendation
- 2021-08-28 19:45:59
- OfStack
Moq is Mock you. The pronunciation can be read as Mock ~ you. Is a kind of Mock framework. Used for the Mock test in the test. Mock means analog. Mock is a technique for simulating objects.
Test method
// Prepare Mock IFoo Interface
var mock = new Mock<IFoo>();
// Configure the method to prepare for impersonation when calling the DoSomething Method and pass the parameter "bing" Return to the true
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);
// In the parameters of the method, the out Parameter
// out arguments
var outString = "ack";
// When the call TryParse Method, out Parameter return "ack", Method returns true, lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref Parameter
var instance = new Bar();
// Only in use ref Called, the following test will be matched
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
// When the method returns a value, you can also access the returned value
// You can use multiple parameters here
mock.Setup(x => x.DoSomething(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
// Throw an exception when called
mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>();
mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command");
// Delay the result returned by calculation
mock.Setup(foo => foo.GetCount()).Returns(() => count);
// In every 1 Returns a different value on the second call
var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCountThing())
.Returns(() => calls)
.Callback(() => calls++);
// No. 1 1 Return from the second call 0 , Under 1 Second is 1 , By analogy
Console.WriteLine(mock.Object.GetCountThing());
Matching parameter
// Arbitrary value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
// The supplied value must match 1 Functions , lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);
// Matching 1 Range of
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);
// Matching regular expressions
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");
Attribute
// Common attribute
mock.Setup(foo => foo.Name).Returns("bar");
// Multilayer attributes
mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz");
// The value of the expected setting property is "foo"
mock.SetupSet(foo => foo.Name = "foo");
// Or directly verify the assignment
mock.VerifySet(foo => foo.Name = "foo");
Set a property so that its value is tracked automatically
// Begin "tracking" Property of sets/gets
mock.SetupProperty(f => f.Name);
// Provide 1 Default values
mock.SetupProperty(f => f.Name, "foo");
// Now, you can :
IFoo foo = mock.Object;
// Saved value
Assert.Equal("foo", foo.Name);
// Reset 1 Values
foo.Name = "bar";
Assert.Equal("bar", foo.Name);
You can also prepare all properties
mock.SetupAllProperties();
Events
// Throw 1 Events
mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));
// Events in multilayered descendants
mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));
// When Submit When the method is called, throw the 1 Events
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// Throwing an exception triggers the underlying behavior of the object
// You may need to do assertion processing later
// Throw 1 Custom events
public delegate void MyEventHandler(int i, bool b);
public interface IFoo { event MyEventHandler MyEvent; }
var mock = new Mock<IFoo>();
...
// Pass custom event parameters
mock.Raise(foo => foo.MyEvent += null, 25, true);
Callback
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute("ping"))
.Returns(true)
.Callback(() => calls++);
// Using the parameters of the call
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
.Returns(true)
.Callback((string s) => calls.Add(s));
// Use generic syntax
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
.Returns(true)
.Callback<string>(s => calls.Add(s));
// Use multiple parameters
mock.Setup(foo => foo.Execute(It.IsAny<int>(), It.IsAny<string>()))
.Returns(true)
.Callback<int, string>((i, s) => calls.Add(s));
// Callbacks before and after calling
mock.Setup(foo => foo.Execute("ping"))
.Callback(() => Console.WriteLine("Before returns"))
.Returns(true)
.Callback(() => Console.WriteLine("After returns"));
Validation
mock.Verify(foo => foo.Execute("ping"));
// Provides a custom error message when validation fails
mock.Verify(foo => foo.Execute("ping"), "When doing operation X, the service should be pinged always");
// A method that has never been called
mock.Verify(foo => foo.Execute("ping"), Times.Never());
// At least it has been called 1 Times
mock.Verify(foo => foo.Execute("ping"), Times.AtLeastOnce());
mock.VerifyGet(foo => foo.Name);
// Validate an assignment to a property .
mock.VerifySet(foo => foo.Name);
// Validate setting a specific value for a property
mock.VerifySet(foo => foo.Name ="foo");
// Verify matching parameters
mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive));
Customize Mock behavior
The behavior of Mock is divided into strict Strict and loose Loose, and the default is loose. In strict mode, using any behavior that is not specified will throw an exception, in loose mode, no exception will be thrown, the method will return a default value or an empty array, and so on.
var mock = new Mock<IFoo>(MockBehavior.Strict);
If the implementation of the base class is not overridden, the base class will not be called by default, which is required in Mock Web/Html controls.
var mock = new Mock<IFoo> { CallBase = true };
To create an automatically recursive Mock, the Mock object will return 1 new Mock object for any of its members.
// Arbitrary value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
// The supplied value must match 1 Functions , lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);
// Matching 1 Range of
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);
// Matching regular expressions
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");
0
Centralized Mock instance creation and management: You can use MockRepository to create and validate all Mock objects and set MockBehavior, CallBse, and DefaultValue constraints in one place.
// Arbitrary value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
// The supplied value must match 1 Functions , lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);
// Matching 1 Range of
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);
// Matching regular expressions
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");
1
Others
// Arbitrary value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
// The supplied value must match 1 Functions , lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);
// Matching 1 Range of
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);
// Matching regular expressions
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");
2
Advanced features
// From Mock Instance retrieval Mock Object
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 IFoo mock The interface has been implemented IDisposable :) disposableFoo.Setup(df => df.Dispose());
// Custom matching
mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>(); ...
public string IsLarge()
{
return Match<string>.Create(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}