Unit Test .NET Business Objects Using Nmock Library

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:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as