RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
你可能遇到了下面的问题
关闭右侧工具栏
Introduction to NMock
  • 作者:xiaoxiao
  • 发表时间:2020-12-23 10:39
  • 来源:未知

Introduction to NMock

by Hsue-Shen Tham

Mocking

In many cases when unit testing, developers will come across a piece of functionality that is hard to test given the dependencies on other classes or components of the system. One technique often used to solve this problem is mock objects. The idea of mocking is to allow the class under test to be unit tested in isolation. Mock objects allow dependent classes to be replaced with mock versions. These mock objects are then passed to the class under test. Hence the dependencies are replaced by the mock versions, while the unit under test still thinks it is dealing with the real objects.

Traditionally mock instances were hand coded, but nowadays there are many tools and frameworks available to make mocking easier in either the Java world or the .NET world. There are 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

Mock tools can normally be categorized into two types, dynamic or static. Static mock tools generate mock implementations of the dependencies as extra classes. These are 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 are normally more popular and preferred to static mocking tools as they are much easier to use and do not create any extra classes. However dynamic mocks are not type safe as compared to static mocks.

Using NMock

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

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

Example

Lets start with a simple Hello example where we will test the Greet() method of the Hello class. This class depends on a Person object and will greet the Person according to his name. This is not a normal case where you would normally use mock objects but it’s a simple enough example to start and understand the basics of using NMock.

We define an interface for a person as follows:

public