From:http://www.cnblogs.com/wjiang/archive/2010/02/21/1670632.html
MOQ is the mock you framework, so the idea is a mock framework similar to Mockery,jmock. is a. NET open source project on Google
Project title page |
Related Downloads |
http://code.google.com/p/moq/ |
Http://code.google.com/p/moq/downloads/list |
Let's talk about the general process of testing with mock-up:
The 3.x version of MOQ has been different from the past, thanks to the. net3.x for everyone to bring the lambda expression, Linq.
Talk about the advantages of MOQ:
A. Fully open source. I don't have much to say about the benefits of open source, but the number of Apache projects is quite a bit less than that of the Java community.
B. Easy to learn and easy to use. MOQ's design principle is "to obtain good reconstruction ability with very low threshold" in my opinion, MOQ is the most natural mock that I have used to get started.
Several important classes in MOQ (detailed in subsequent articles):
Mock<t>: Through this class we can get a Mock<t> object, T can be an interface and a class. It has a public object property, and this is what we moq for our simulations.
It: This is a static class for filtering parameters.
Mockbehavior: The behavior used to configure Mockobject, such as whether to auto-mock.
The Mockfactory:mock object factory is capable of mass production of mock objects that unify custom configurations, and can also be tested in batches for mock objects.
Match<t>: If you first think it's not enough, use Match<t>, which allows you to fully customize the rules.
Primary Knowledge MOQ:
To create a new test, we demonstrate the use of a MOQ with three lines of code.
[TestMethod ()] [Owner (Wjiang)]public void MoqTest0 () { //make a Mock Object by Moq var mo = new MOCK<TARGETINTERFACEONE&G t; (); Setup our Mock Object mo. Setup (p = p.methodwithparamandresult ("abc")). Returns ("123"); Assert it! Assert.AreEqual ("123", Mo. Object.methodwithparamandresult ("abc")); }
Description
New Mock<t> Returns a mock object that we can receive with Var, which makes it easier to write,mock<t> has an object property that stores our instance of a mock object.
The setup parameter is a lambda Expression, which we can understand as: "When the mock object P calls the Methodwithparamandresult method and the argument is" ABC ". With a return ("123") we can understand that the value returned (in the case of the previous setup) is "123". In this way, we populate a "pseudo-object" behavior, we only let it do one thing: when we call Mo. "123" is returned when the Object.methodwithparaandresult method and the parameter is "ABC".
In fact, we can not only connect the returns method behind the setup, but also the methods such as throws, verify and so on. The Setup method returns a ISetup object and looks at the definition of ISetup:
Public interface Isetup<tmock, tresult>: Icallback<tmock, Tresult>, Ireturnsthrows<tmock, TResult>, Ireturns<tmock, Tresult>, Ithrows, Inever, Iverifies, ihideobjectmembers where Tmock:class
Well, is chained programming, ISetup interface inherits a lot of interfaces, here we notice ireturns<tmock,tresult>, see Ireturns<tmock, tresult> definition:
Public interface Ireturns<tmock, tresult>: ihideobjectmembers where Tmock:class.
Inside there is a method:ireturnsresult<tmock> returns<t> (func<t, tresult> valuefunction);
So we can also write this code:
Mo. Setup (p = p.methodwithparamandresult ("abc"))
. Returns ("123")
. Callback (...)
. Throws (...)
. Verifiable (...);
Oh, this code is very natural to understand. MOQ design is not very humane it.
The previous article introduced MOQ and gave an example of getting started. The following is a parameter match in MOQ. One way to look at mock<t> first.
Public isetup<t> Setup (expression<action<t>> Expression);
Familiar with. NET Framework, especially friends who have developed an MVVM-based WPF application, should be familiar with the two generic delegates action<t> and prediect<t>, the meaning of these two delegates is concise, the former means that given a parameter and then a behavior, The latter indicates the premise of the Act.
If we have an interface Ia,ia has a method to sign string MethodA1 (stringidentity). So how do we simulate an object that implements the IA interface MethodA1?
var mo = new mock<ia> (); Mo. Setup (p = p.methoda1 ("50")). Return ("Hello, Mocker");
This example is the same as the previous one, where the additional explanation is that the parameter type of return depends on the return type of the method, and if we return the MethodA1 to void, then we cannot return the method, because the string type is returned, so we can return it.
Of course, the method parameter has a large selection of cocoa values, "51", "52", "53", "54", "55", "56" ... What if we had a setup of one? I have a grand launch of two class:it,match<t>.
First of all, It,it is good for matching numbers, string parameters, and it provides several static methods (from the official API documentation for MOQ):
The first method of the parameter expression<predict<tvalue>> type, when you need some type and this type to be judged by the code can use it.
The second method has no parameters, so long as the TValue type can match successfully.
The third method is used to match the parameters between the two TValue type values. (range parameter can set opening and closing range)
The fourth one is to match the regular expression. (String type parameter only)
As an example:
[TestMethod] [Owner (Wjiang)]public void MoqTest1 () { var mo = new mock<targetinterfaceone> (); Mo. Setup (p = p.methodwithparamandresult (It.isregex ("^god.*$"))). Returns ("Bless Me"); Mo. Setup (p = p.methodwithparamandresult (it.is<string> (param = param. IndexOf ("Evil") >= 0))). Returns ("Away from Me"); Mo. Setup (p = p.methodwithparamandresult (It): assert.areequal ("Bless Me", Mo. Object.methodwithparamandresult ("God Comes")); Assert.AreEqual ("Away from Me", Mo. Object.methodwithparamandresult ("Evil is Here"); }
But it provides a little bit of functionality, and we can customize the matching validation rules. This is the use of match<t>.
Match<t> is a static class whose value exposes a static method (overloaded with two versions): public static T Create (predict<t> condition, ...).
First look at the following code for easy explanation, we write a static helper class for parameter matching.
[testmethod ()] public void Moqtesta () {var mo = new mock& Lt Targetinterfaceone> (); Mo. Setup (p = p.methodwithparamandresult (Matchhelper.custommatcher ("abc"))). Returns ("123"); Assert.AreEqual (Mo. Object.methodwithparamandresult ("abc"), "123"; Assert.isnull (Mo. Object.methodwithparamandresult ("Newyorktimesbyflex")); }public Static class Matchhelper {public static string Custommatcher (String arg) { return match<string>. Create (P = = p.equals (ARG), () =>null); } public static ienumerable<string> Contains (string key) {return Match<ien Umerable<string>>. Create (P=>p.contains (key)); } }
For us, Custommatcher (string arg) and contains (string key) are the validation methods. Compared with the previous example, p = = P.methodwithparamandresult (...) The things inside are replaced by our own methods. Another contains method can be used to satisfy a requirement that a given parameter is an iterative type that matches only when a specific element is included
Raise
If you say you will use Setup, then raise is easier. Note here that it is a no return value type.
Mockview.raise (v = v.selectionchanged + = null, new OrderEventArgs {order = New Order ("MOQ", 500)});
Callback
Callback, as the name implies is a callback. Using callback allows us to be notified when a method that matches with a particular parameter is called. For example, we need to know that a method has been called several times in a test to do this:
[TestMethod] public void MoqTest2 () { var mo = new mock<targetinterfaceone> (); int counter = 0; Mo. Setup (P = p.methodpure ()). Callback (() = counter++); Mo. Object.methodpure (); Mo. Object.methodpure (); Assert.AreEqual (2, counter); }
In this code we followed the Setup method with a callback method (or the Callabck method implementation that called ISetup). This code means that the action delegate in callback is executed when the Methodpure method is called.
Call two times methodpure (), the test result proves that two times counter has been accumulated.
Verify
Sometimes we don't focus on the return of the method, but rather on whether a method is called internally.
Then we used the Verify/verifyall. At the same time there is a useful type times, which specifies how many calls should be called. Throws an exception if the validation fails.
[TestMethod ()] public void MoqTest3 () { var mo = new mock<targetinterfaceone> (); Mo. Setup (P = p.methodpure ()); Mo. Setup (p = p.methodwithparam ("123")). Verifiable ("It should be invoked"); Mo. Object.methodpure (); Mo. Object.methodwithparam ("123"); Mo. Verify (P = p.methodpure (), times.atleastonce ()); Mo. Verify (p = p.methodwithparam ("Thto"), Times.atleastonce (), "This method invoking of Methodwithparam () With the parameter: \ "Thto\" was not happened "); Mo. Object.methodpure ();}
If you call mo.verify (p = = p.methodpure ()) before Methodpure, the exception is thrown because it does not meet the criteria: it is called at least once before the Verify is executed.
About Verify and Verifyall
These two methods validate all the setup methods of a mock object, so what's the difference? Notice that the Green Font section of the above code has a verifiable method that can be understood to add a validation token for this setup. When Setup (P=>p.methodpure ()) is not available, we will only validate Methodwithparam ("123") when we use call verify () instead of whether methodpure () is invoked.
Unit Tests Tool-<what is ' Mock you ' > the introduction to MOQ #Reprinted #