Brief introduction and simple example of mock-up under unit test--MOQ frame

Source: Internet
Author: User

1. Why use Mock?

These problems are often encountered during the testing process:

(1) The real object has an indeterminate behavior (produces unpredictable results, such as stock quotes).  

(2) Real objects are difficult to create.  

(3) Certain behaviors of real objects are difficult to trigger (such as network errors).

(4) Real objects make the program run slowly.  

(5) The real object has (or is) a user interface.  

(6) The test needs to ask the real object how it was called (for example, the test might need to verify that a callback function was called).  

(7) Real objects do not actually exist (this is a common problem when it comes to dealing with other development groups, or new hardware systems).  

With the help of mock objects, we can solve all the problems mentioned above.


2. How do I use Mock?

(1) for a variety of reasons, an object needs to be simulated by a mock ;

(2) Use an interface to describe the object;

(3) for testing purposes, Implement this interface in a mock object.


3. Test Preparation:

(1) Download installation NUnit, address:

Note: After extracting the MOQ, use the Moq.dll in the NET35 file. If they are not compatible, they can be swapped for other versions (NET40, Net40-requirescastle).

(2) Add two references nunit.framework, moq.dll to the test case project.


4. Test Example:

(the addition, subtraction, multiplication, and arithmetic operations are implemented in a class, and the other class is exponentiation, but not yet implemented, instead of using a mock.) )

(1) There is a method in the source program (powerfunctionaction) that needs to be simulated with mock

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace countfunction{public    class Methods    {        //console application, program entry        static void Main (string[] args)        {        }        Declaration Interface        Private ipowerfunction _actionnum;        No parameter constructor public        Methods () {}        //constructor public        Methods (ipowerfunction actionnum)         {            //property Initialize (become a member of a property via the parameter interface)            this._actionnum = Actionnum;        }        Power operation (exponent is an integer) public        double Powerfunctionaction (double A, int num)         {            //the interface is called through member functions, It relies on other interface implementations (if it has not yet completed development)            return This._actionnum.powerfunctiongetvalue (a,num);        }         ...... Other functions (methods) implemented        #endregion    }}

(2) Special interface (interface written specifically for "methods that require mock simulation")

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace countfunction{//<summary>//    Power Arithmetic interface///    </summary> public    interface Ipowerfunction//Write an interface    {        double powerfunctiongetvalue (double A, int num) for an object that requires a mock substitution;}    }
(3) Test project

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using nunit.framework;using countfunction;using moq;namespace countfunction.tests{[testfixture] public class Progra Mtester {#region Test//1 using a mock.                Mock instead of interface ipowerfunction (that is, mock = ipowerfunction) Private ipowerfunction prvgetmockpowerfunction () { 1.1 Declaring a generic mock object (mock = ipowerfunction) mock<ipowerfunction> mockobject = new MOCK&L                T;ipowerfunction> (); 1.2 Set the mock return value-the content represented by Mockobject.setup (M = M.powerfunctiongetvalue (2, 3)).                Returns (8);            1.3 Return mock object (use substitution) return mockobject.object; }//2.                Call mock [Test (Description = "Power Operation Powerfunction ()")] public void testpowerfunction () { 2.1 Calls a private function member, creating a mock (this ipowerfunction = mock) that replaces the interface ipowerfunctIon Powfun = This.prvgetmockpowerfunction ();                2.2 Instantiate an object that is substituted with a mock Methods Methods = new Methods (powfun); 2.3 Values are passed for the composite interface, and double result = methods is called.                Powerfunctionaction (2, 3);            2.4 Set assertion, Judge Assert.AreEqual (8, result); } //...... Test for other functions (methods) #endregion}}

NUnit, Moq:

Installation Detailed: http://blog.csdn.net/wangqingbo0829/article/details/43975243



Brief introduction and simple example of mock-up under unit test--MOQ frame

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.