. NET Unit Test NMock

Source: Internet
Author: User

. NET Unit Test NMock

NMock is a dynamic agent-based mock simulation object class library under the. NET Platform for C # development. Mock objects make testing easier, and it does not require all other components to be truly implemented when testing a single component or a single class.         In other words, we can just test a class, NMock generated by using dynamic proxy at runtime, which allows the simulation of object dynamic definition, do not need to add any additional classes. Typically, an implementation of a simulation is created based on the interface being relied upon, NMock supports impersonation of interfaces and classes, and it also supports property impersonation. It's easier to figure out a bug than to test a complete object-relational tree. Mock objects are typically used in test-driven development.

    • Why do I need a mock

The basic principle of unit testing should be to validate only one method at a time, but if you encounter a situation where:

The test method relies on other things that are difficult to manipulate, such as: Network, database. Or the code you're testing depends on the rest of the system, or even many other parts of the system. In this case, if you are not careful, you may eventually find yourself accidentally initializing every component of the system, all just to create the necessary operating environment for a particular test. This not only takes a lot of time, but it's a lot of coupling factors that have been introduced into the test, and it's hard to get to the "unit" test. What should we do? This is a mock test method that comes in handy. The literal meaning of mock English is: ridicule, imitation, deception. With mock, we can create a lot of alternatives to real objects and use them in test cases.

    • Under what circumstances to consider using mock

1) The real object has an indeterminate behavior (e.g., the program needs to get the real-time price of the stock through a Web service)

2) objects are difficult to create (such as the system environment is difficult to initialize)

3) Certain behaviors of real objects are difficult to trigger (such as network error, database ID self-increment sequence overflow)

4) Real objects make the program run slowly

5) real objects contain UI and other inconvenient testing factors

6) The test needs to ask how the real object is called (as in the case of an asynchronous call, the Callbak function needs to be verified)

7"          real objects are not present (such as relying on other project groups or requiring a new hardware system system)

    • steps for Mock testing
    • The test code First refers to the NMock framework

1) define an interface to describe this object

2) Product code to implement this interface

3) the mock object in the test implements this interface

Here's a quick tutorial that uses NMock:

Example Now let's do a simple "hello" example, test the Greet () method of the Hello class, the Hello class depends on a person object, and will send congratulations (Greet) to the corresponding account based on the person's name. This example is very simple, but it is not used to simulate objects, but it is very suitable to understand nmock.

public interface IPerson {string Name {get;}} Then you define the Hello class with the Greet method, and you can send a congratulatory message based on the name of IPerson. public class Hello {IPerson person;     Public Hello (IPerson person) {This.person = person; } public String Greet () {return ' Hello ' + person.     Name; } }

We can see that the Hello class is dependent on the IPerson interface.

Before we proceed with the development of the Hello class, let's learn some basic knowledge about nmock. Using NMock it is easy to create a mock object based on a given interface or class;

1) First you instantiate a mock object, which is constructed to pass the type of interface or class you want to simulate to a mock object as a build parameter;

2) then you need to record the behavior of the mock object and finally get an example of a mock type by using the properties of the mock object. The following is a mock object of the simplest form, which is created based on the IPerson interface and does not record any behavior.

Notifies nmock which interface or class you are simulating imock Mockperson = new Dynamicmock (typeof (IPerson)); Gets a mock instance of the specified type IPerson person = (IPerson) mockperson.mockinstance; However, if we do not record what the mock object should do or what needs to be done before it can be used, So actually the mock object is useless; In the following example, we will record and set the value of the Name property of the IPerson. //Notify NMock which interface or class you are simulating imock Mockperson = new Dynamicmock (typeof(IPerson)); //Set value MOCKPerson. Expectandreturn ("Name", "John"); //Gets a mock instance of the specified type iperson person = (IPerson) mockperson.mockinstance;  NMock has a very long and useful list of Expect methods that we can use to set the behavior of the mock object, such as when method A is called to return B, or only when method A is called with parameter C, or when the A method is called and throws an exception E, even we can tell the mock object it Don't expect to be able to call method A at all. The simple example above shows that we want the Name property to be called only once, and the string "John" will be returned when the property is accessed; Note we want the Name property to be called only once, and we can verify this by calling the Verify () method of the mock object. The expected test person on the mock object. Verify ();

This is a brief list of the methods that are expected to be set:

Expect (String methodName, object[] args)

Expectandreturn (String MethodName, Object ReturnVal, object[] args)

Expectandthrow (String methodName, Exception exceptionval, object[] args)

Expectnocall (String methodName)

Now that we have all the basic conditions set, we can simply apply nmock to the test of the Hello class.

This is our test class:

[Testfixture] public class Hellotest:assertion{    [test]     public  void testexpect ()     {         //Analog Dependent         imock person  = new dynamicmock (typeof (IPerson));         //set the value         person. Expectandreturn ("Name",  "John");         hello hello = new hello ( (IPerson)  person. Mockinstance);         assertequals ("Hello john",  hello. Greet ());         //Test  Name  Whether the property was only called once          person. Verify ();     }}

Related Article

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.