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).

Conclusion

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.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists