ASP. Mvc3-the easier to run Unit Tests by MOQ #Reprinted #

Source: Internet
Author: User

From:http://www.cnblogs.com/techborther/archive/2012/01/10/2317998.html

Unity was investigated a few days ago. Now the task for me is to let me investigate MOQ.

The following is the information you find, summarize and practice the content. If there is a place to express and understand the error. I beg to correct.

What is MOQ?

Moq (English pronunciation is mock-you or just mock) is a target. NET development of the simulation library, it is fully utilized from the beginning. New features (lambda expressions) for NET3.5 (LINQ expression tree) and c#3.0. Its goal is to allow simulations to integrate with existing unit tests in a natural way, making it simpler and more intuitive to avoid developers being forced to rewrite tests or high-cost learning testing frameworks. This makes it a highly productive, type-safe, refactoring-friendly simulation library.

Where did you get the MOQ?

If you have read my other articles, we can use the plugin NuGet in vs directly to get MOQ and refer to the specified project.

Otherwise, we can get the latest version of MOQ from http://code.google.com/p/moq/.

What can be simulated? Limitations

First, the simulated class cannot be sealed.

Second, you cannot directly simulate static methods. Because MOQ can only create mock object instances. In this case, the indirect solution is that we can wrap a layer outside of the object to be simulated and simulate the new object. This mode is called the adapter mode.

Usually we test a method, it is possible to call several service. But the cost of every visit to these service is high. We can simulate the way it accesses the service and simulate the results of a return response based on different requests.

MOQ principle

How did MOQ do that? It requires only one interface type to produce an object? Yes, that's it. MOQ use Castle dynamicproxy to complete this task. The basic principle is that it uses the Emit function of the reflection mechanism to dynamically generate an empty type (i.e. all interfaces are instantiated, but without any function, just a skeleton of the program). So the ability to mock is to use the dynamicproxy mechanism to quickly produce a dummy object that mimics the behavior of a real object.

Important members of the MOQ

Mock

With this class, we can get a mock<t> object. T can be an interface, or it can be a class. It has a public and virtual property. Let's look at the example below:

Define interface to is mocked public        interface Ifake        {            bool DoSomething (string actionname);        }        Define the test method        [TestMethod] public        void Test_interface_ifake ()        {            //make a mock Object by moq< C9/>var mo = new mock<ifake> ();            Setup our mock object            mo. Setup (foo = foo. DoSomething ("Ping"))            . Returns (true);            Assert it!            Assert.AreEqual (True, Mo. Object.dosomething ("Ping"));        }

In the upper code, we pass the generic parameter ifake to create an instance of Mock<ifake> to simulate the interface Ifake.

Next we'll call the Setup () method to create our mock object. Note that the parameter of the Setup method is a lambda expression. We can understand this: when the Impersonated object Foo calls its own method dosomething (), and the parameter is ping. Add suffix return (true) we can understand that: the front of the request returned the result is true. This is the return value that we specified. When a request is called the DoSomething () method. If the parameter passed in is ping, then we will return true. Next, we add an assertion to determine if we can get the expected results.

Note: Foo is just a word used as a generic substitute for real things, especially when discussing technical ideas and questions.

It

This is a static class that defines a static generic method: Is<tvalue>, Isany<tvalue>, Isinrange<tvalue>, and Isregex. To filter the parameters. Take a look at the example below:

Public interface Iemailsender        {            bool Send (string subject, string body, string email);        }  [TestMethod]        public void User_can_send_password ()        {            var emailmock = new mock<iemailsender> ();            Emailmock            . Setup (sender = sender. Send (It.isany<string> (), it.isany<string> (), it.isany<string> ()))            . Returns (True);        }

Any time the Send () method is called, as long as the passed argument is any string, we define that he will return true.

We can also customize a rule based on the advantages of lambda:

var productrepository = new mock<iproductrepository> ();            Productrepository            . Expect (p = p.get (it.is<int> (id = = ID > 0 && ID < 6))            . Returns (Newproduct.object);

This way we can set this ID to return a new object when it is between 0 and 6. The other methods mentioned above, we can refer to the tutorial here Moq ' s QuickStart

In addition, the enhanced version of this class is Match<t>, and you can customize the simulation rules completely.

Mockbehavior

This class is used to simulate the behavior of an object. It's like whether to emulate by default mode. Let's take a closer look at his definition:

namespace moq{    //Summary:    //     Options to customize the behavior of the mock.    Public enum Mockbehavior    {        //Summary:        //     causes the mock to always throw a exception for invocations tha t have        //     a corresponding setup.        Strict = 0,        ////        Summary:        //would     never throw exceptions, returning default values when necessary (Nu ll        //     for reference types, zero for value types or empty enumerables and arrays).        Loose = 1,        /////        Summary:        //     Default mock behavior, which equals Moq.MockBehavior.Loose.        Default = 1,    }}

Now, take a look at the following example:

New Mock<ifake> (mockbehavior.strict);

Specifies that the mock behavior is accurate and throws an exception if it does not follow the expected setup.

Mockfactory

This is a factory for simulating objects, and we can not only customize the configuration to create mock objects, but also test them in batches. Take a look at the example below:

var factory = new Mockfactory (mockbehavior.strict) {defaultvalue = Defaultvalue.mock};            Create a mock using the factory settings            var foomock = factory. Create<ifake> ();            Create a mock overriding the factory settings            var barmock = factory. Create<iemailsender> (mockbehavior.loose);            Verify all verifiable expectations on all mocks created through the factory            factory. Verify ();

In the front, we have introduced the traditional way of creating mock objects, which do not really call methods, but simply to execute some assumptions: if ... Then return ....

In the example below, I will continue to introduce some basic and important methods in the Mock<t> class.

Verification

Sometimes, we want to determine whether a method has been called, or even how many times it has been called. A more traditional approach is to use the Verify () method. Take a look at the example below:

Mock. Verify (foo = foo). DoSomething ("Ping"), Times.once ());  

The code above tries to verify that dosomething ("Ping") needs to be called and is called only once. Out of the once option, there are more options available for you to decide how many times this method needs to be called. such as: AtLeast, Atleastonce, Atmost, atmostonce, between, Equals, exactly, never, and once

Once we have simulated the object, validation will be an easy task to take a look at the example below:

[TestMethod] public void test_findbyname_getcalled () {//create some mock data ilist& Lt            product> products = new list<product>{new Product {ProductId = 1, Name = "C # Unleashed", Description = "Short Description here", Price = 49.99}, new Product {ProductId = 2, Name = "ASP. ", Description =" Short Description here ", Price = 59.99}, new Product {ProductId = 3, Name =" Sil            Verlight Unleashed ", Description =" Short Description here ", Price = 29.99};                mock<iproductrepository> mock = new mock<iproductrepository> (); Mock//. Setup (sender = sender. FindByID (It.isany<int> ()))//. Returns (int s) = products. Where (//x = X.productid = = s).            single ()); Mock.            Object.findbyid (1); Mock.        Verify (x = X.findbyid (1), times.once ());  }  } 

In the above example, there are two places worth noting.

The first is a mock. Object.findbyid (1). To make everything easier in this case, we call the mock directly. The method of the object. Why is it? Because our case is only concerned with the number of times this method is called, not the return value. Of course, we seldom do so in practical applications.

Second, have you noticed the sentence that was commented out. It's just a "if, then" sentence. This means that if Setup is ready, it returns the values we define.

Due to the limited time of the survey, there is much more to the point where I am not involved in mock-giving forces. We can go and check the official information. Welcome to the joint discussion.

Resources

Http://stephenwalther.com/blog/archive/2008/06/12/tdd-introduction-to-moq.aspx

http://code.google.com/p/moq/wiki/quickstarthttp://codeclimber.net.nz/archive/2009/10/23/10- resources-to-learn-moq.aspxhttp://blogs.clariusconsulting.net/kzu/tag/moq/

Http://blog.miniasp.com/post/2010/09/16/ASPNET-MVC-Unit-Testing-Part-03-Using-Mock-moq.aspx/HTTP dotnetslackers.com/articles/aspnet/built-in-unit-test-for-asp-net-mvc-3-in-visual-studio-2010-part-2.aspx# S4-using-moq-framework

ASP. Mvc3-the easier to run Unit Tests by MOQ #Reprinted #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.