Introduction to NMock

Source: Internet
Author: User
Tags throw exception versions
Introduction to NMockby Hsue-shen Tham

Mocking

In many cases when unit testing, developers would come across a piece of functionality that's hard to test given the Depen Dencies on other classes or components of the system. One technique often used to solve this problem is a mock objects. The idea of mocking was to allow the class under test to being unit tested in isolation. Mock objects allow dependent classes to being replaced with mock versions. These mock objects is then passed to the class under test. Hence the dependencies was replaced by the mock versions while the unit under test still thinks it was dealing with the RE Al objects. Traditionally mock instances were hand coded, but nowadays there is many tools and frameworks available to make mocking E Asier in either, the Java world, or the. NET World. There is plenty of materials available describing the fine art of creating mock objects either manually or using some of The popular Java mocking tools. Rather than going down the same "path in Java", this article aims-to-touch on the UNFAMiliar area of mocking in. NET using one of the more popular mocking tools in. Net.

Static vs . Dynamic

The Mock tools can normally is categorized into the types, dynamic or static. Static mock tools generate mock implementations of the dependencies as extra classes. These is compiled together with the source ensuring type safety check. Dynamic mock tools generate the mock implementations at runtime without adding any additional classes. Dynamic mocking tools is normally more popular and preferred to static mocking tools as they is much easier to use and D o not create any extra classes. However dynamic mocks is not type safe as compared to static mocks.

Using nmock

NMock is a mocking tool for C # that's based on dynamic proxies. It makes use of the proxy pattern, which allows a class to implement a interface and redirect calls to another object act ing as a proxy. NMock generates mock implementations using dynamic proxies at runtime. This allows mocks objects to being dynamically defined without adding any extra classes.

Normally, interfaces of the dependencies would be a used to create the mock implementation. NMock supports mocking both interface and classes. In addition it also supports properties mocking. Following'll be a quick tutorial on using NMock:
Example

Lets start with a simple Hello example where we'll test the Greet () method of the Hello class. This class depends on a person object and would greet the person according to his name. This isn't a normal case where do you would normally use mock objects but it's a simple enough example to start and Understa nd the basics of using NMock.

We define an interface for a person as follows:

Public interface IPerson
{
	string Name {get;}
}

Then define hello class with a Greet method, which greets hello followed by the IPerson ' s Name.

public class Hello
{
	IPerson person;

	Public Hello (IPerson person)
	{
		This.person = person;
	}

	Public String Greet ()
	{
		return ' Hello ' + person. Name;
	}
}

As we can see here, Hello class have a dependency on ipersonbefore we go no further with the Hello class, let's learn some Basics about NMock. In NMock It's really easy-to-create a mock object based on a given interface or class. It is a three steps process where, first you instantiate a Mock object by passing in the type of the interface or class th At your is trying to mock. Then your would record the behaviour of the mock object and finally you get a working instance of the mock type through the Properties of the Mock object. Here's an example of what we create a mock instance in the simplest form without recording all behaviour based on the IPer Son interface.

Tell NMock which interfaces or classes is mocking Imock mockperson
= new Dynamicmock (typeof (IPerson));
Get a mock instance of the specified type
iperson person = (IPerson) mockperson.mockinstance;

However normally a mock instance is isn't really useful unless we record the behaviour of what it's supposed to does or what To expect before it is used. In the following example, we record and setup the values for the IPerson's Name property:

Tell NMock which interfaces or classes is mocking Imock mockperson
= new Dynamicmock (typeof (IPerson));
Set up the values person
. Expectandreturn ("Name", "John Doe");	
Get a mock instance of the specified type
iperson person = (IPerson) mockperson.mockinstance;

NMock has a long list of useful Expect methods, which can is used to setup the behaviours of the mock object such as when Method A is called return B, or as return B when method A was called with parameter C, or throw Exception E if method a I s called or even tell the mock object of it should not being expecting call to method A at all. What's done above are simply saying that we expect the Name of the property would be accessed once if it is acces Sed it would return the string "John Doe". Note that we expect the property Name to being called once only. We can verify this by calling the Verify () method on the mock object.

Verify expectations on the mocking objects person
. Verify ();

Here's a quick list of what's available for setting up expectations:

Expect (String methodName, object[] args)
Expectandreturn (String MethodName, Object ReturnVal, object[] args)
Expectandthrow (String methodName, Exception exceptionval, object[] args)
expectnocall (String methodName)

Now gathering all the basics, we can easily apply it with our test for Hello class.
So in our test:

[Testfixture]
public class hellotest:assertion
{
	[Test] public
	void Testexpect ()
	{
	//Mock the dependency
		Imock person = new Dynamicmock (typeof (IPerson));	
	
	Setting up values person
		. Expectandreturn ("Name", "John Doe");			

		Hello hello = new Hello ((IPerson) person. mockinstance);			
		Assertequals ("Hello John Doe", hello.) Greet ());

		Verify that Name property was only accessed once person
		. Verify ();
	}
}

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.