Unit Test .NET Business Objects Using Nmock Library

Writing unit script code for your complex business objects in a test-driven development environment really gets difficult, because business classes may have too many external dependencies (high coupling) on other objects.

It sometimes won’t be possible for limited-budget projects to set up development environments appropriately and configure them for unit testing. Developers can overcome these issues by using mock test objects.

[login] By creating mock business objects (without relying on real implementations of your complex business objects) you can unit test a single class at a time. Mock objects are simulated objects that replicate the behavior of your business objects, and you can use these mock objects in your actual unit test script code.

Using Nmock Library

There are few Microsoft .NET-supported mock testing frameworks available — Nmock is one of them. Nmock can also be easily integrated with Nunit testing framework. Nmock is free, and 2.0 is the latest version that works with both .NET framework versions 1.1 and 2.0. You can download it from this Nmock site.

Nmock is a unique mock testing library with the following characteristics:

      * Like any other unit testing framework, developers need to define their expectations. What you are expecting as output?

* Mock objects are dynamic in nature and generated on the fly, based on implemented interfaces.

* Your test case will fail if the actual output doesn’t match up with the expected output.

* Error messages show detailed descriptions of the error.

In this article I will show you an example of how to use Nmock library with .NET framework version 2.0.

Setup the Nmock Testing Environment

To develop the sample application, I used visual studio 2008 with .NET framework 2.0. For unit testing, I used Nunit version 2.5.4, freely downloadable from the Nunit site. But in the sample project I have only referenced NUnit.Framework.dll.

I downloaded the Nmock library from the site listed above. Once you unzip it, you’ll get a few dll files. I have only added the reference of NMock2.dll in this sample project — that’s the latest one. This sample application displays common length- and distance-conversion factors while converting one type of length measurement unit to another. For example, the conversion factor value for converting meter to feet is 3.28.

First, in the consol-type C# project, I have created IconversionService interface having the GetConversionRate method. This method takes “from-length” and “to-length” type string parameters and returns the conversion factor (double data type). I have referred to this IconversionService interface in my mock test script.

using System;using System.Collections.Generic;using System.Text;namespace MockTesting.Sample ???{ ???public interface IconversionService ???????{ ???????double GetConversionRate ( string fromlength, string tolength ); ???????} ???}

The ConversionServices class implements the IconversionService interface; the overridden GetConversionRate function is the only method of this class. While converting meters to feet, or mile to kilometer, I have called the GetConversionRate method.

using System;using System.Collections.Generic;using System.Text;namespace MockTesting.Sample  ???{ ???public class ConversionServices : IconversionService ???????{ ??? ??????public double GetConversionRate ( string fromlength, string tolength ) ???????????{ ???????????if ( fromlength.Length <=0 || tolength.Length <= 0 ) ???????????????return 0; ?????????????switch(fromlength) ?????? ?????????????{ ???????? ????????????????case "MET": ?? ???????????????????if (tolength.Trim().ToString() == "FT" ) ???????????????????????return 3.28; ???????????????????break; ????????????????? ????????????????case "FT": ??????????? ??????????????????????if (tolength.Trim().ToString() == "MET" ) ??????????????????????????return 0.3048; ????????????????????break; ????????????????case "MILE": ????????????????????if ( tolength.Trim ( ).ToString ( ) == "KM" ) ????????????????????????return 1.609344; ????????????????????break; ????????????????case "KM": ????????????????????if ( tolength.Trim ( ).ToString ( ) == "MILE" ) ????????????????????????return 0.621371192; ????????????????????break; ????????????????default: ??????????? ???????????????????return 0; ???????? ????????????????????????? ??????????????} ?????????????return 0; ???????????} ?????? ???????} ???}

For calculating the total converted value, for example converting 10 meters to feet, I have created the ConvertTotalValue class. ConvertTotal function of this class calculates the total converted value. If you look at this function code you will see that the GetConversionRate method of IconversionService interface is called for length conversion. I have also created a read-only instance of the IconversionService interface in ConvertTotalValue class and instantiated that in the constructor. This instance will act as a mock.

using System;using System.Collections.Generic;using System.Text;namespace MockTesting.Sample ???{ ???public class ConvertTotalValue ???????{ ???????private readonly IconversionService conversionService; ???????public double ConvertTotal ( string fromlength, string tolength, double totvalue ) ???????????{ ???????????if ( fromlength.Trim ( ).Length <=0 || tolength.Trim ( ).Length <=0 ) ???????????????return 0; ???????????if ( totvalue == 0 ) ???????????????return 0; ???????????return conversionService.GetConversionRate ( fromlength, tolength ) * totvalue; ???????????} ???????public ConvertTotalValue ( IconversionService conversionService ) ???????????{ ???????????????this.conversionService = conversionService; ???????????} ???????} ???}

Next, to show the difference between normal unit testing (Nunit library) and mock testing (Nmock library), I have created two different test methods in the ConversionServicesTest class. In the ShowCorrectLengthConversion test method I've used an object of the ConversionServices class and called the GetConversionRate method to get the conversion factor. Control is passed to the overridden implementation of GetConversionRate function -- if you debug the GetConversionRate function at runtime.

But in the ShowCorrectLengthConversionWithMock method I have not created any instance of ConversionServices class to get the conversion factor. Instead of the real implementation I have created a mock instance of the IconversionService interface, which is used while calculating the total conversion value. I have created a mock object using the Nmock library function. Please refer to the following code:

Expect.Once.On ( mockconversionService ). ?Method ( "GetConversionRate" ). ?With ( objLengthType.FromLength, objLengthType.Tolength ). ?Will ( Return.Value ( 3.28 ) );

Expect.Once.On will create a mock instance. So, the next time you call the GetConversionRate method with from parameter value "MET" and to parameter value "FT," it will return the conversion factor 3.28. The following code shows the full mock testing code of the ConversionServicesTest class.

using System;using System.Collections.Generic;using System.Text;
using NUnit.Framework;using NMock2;namespace MockTesting.Sample ???{ ???[TestFixture] ???public class ConversionServicesTest
???????{ ???????private Mockery mocks ;
???????private IconversionService mockconversionService ;
???????private ConversionServices objConversionServices = new
ConversionServices ( ); ???????private ConvertTotalValue objConvertTotalValue;
???????[SetUp] ???????public void SetUp ( )
???????????mocks = new Mockery ( );
???????????mockconversionService = mocks.NewMock ( );
???????????objConvertTotalValue = new ConvertTotalValue ( mockconversionService );
???????????} ???????[Test]
???????public void ShowCorrectLengthConversion ( ) ???????????{ ???? ???????????LengthType objLengthType = new LengthType ( ); ???????????objLengthType.FromLength= "MET"; ???????????objLengthType.Tolength= "FT"; ???????????Assert.AreEqual ( objConversionServices.GetConversionRate ( ???????????objLengthType.FromLength, objLengthType.Tolength ), 3.28 ); ????????? ???????????} ???????[Test] ???????public void ShowCorrectLengthConversionWithMock ( ) ???????????{ ???????????????????????????? ????????????LengthType objLengthType = new LengthType ( ); ????????????objLengthType.FromLength= "MET"; ????????????objLengthType.Tolength= "FT"; ????????????Expect.Once.On ( mockconversionService ). ????????????Method ( "GetConversionRate" ). ????????????With ( objLengthType.FromLength, objLengthType.Tolength ). ????????????Will ( Return.Value ( 3.28 ) ); ????????????Assert.AreEqual ( objConvertTotalValue.ConvertTotal ( objLengthType.FromLength, ????????????? ????????????objLengthType.Tolength, 10.0 ), 32.8 ); ????????????mocks.VerifyAllExpectationsHaveBeenMet ( ); ???????????} ???????} ??? ???}

Now, once I run this unit test script code in the Nunit graphical interface, both the function asserts results shows passed (green).


Nmock is the best method stub to simulate complex business objects in your development environment required for unit testing. Enhancements are still in progress for this framework, and hopefully in the near future we will get more features.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS