Welcome!

Microsoft Cloud Authors: Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie, Elizabeth White

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Derek Ferguson on "Pragmatic Unit Testing" An Introduction to NMock

I differentiate what I like to call 'pragmatic unit testing' from the two alternate approaches

I have staunchly advocated what I like to call "pragmatic unit testing" at every client I have been at for the past year. I differentiate pragmatic unit testing from the two alternate approaches to unit testing that I have seen at organizations. The first "alternate approach," which I have seen at 95 percent of .NET organizations, is best referred to as "no time for quality." The other approach, which I have mainly seen at J2EE organizations, can be labeled "quality, even if it puts us out of business."

Between these two extremes, I have tried to follow a path where I use unit tests to accomplish my daily work. I try to build as much resilience and reusability into these unit tests only as my immediate deadlines allow. This means that after a project is finished, I often have a decent-sized set of unit tests that have been created without costing my client anything in terms of development time.

The downside to this approach is: because I haven't spent any extra time in abstracting these unit tests away from their dependencies (since those dependencies happened to exist at precisely the moment of their creation), half of my unit tests typically wind up broken shortly after release, through no cause other than the application's standard usage.

Let me clarify this rather difficult-to-explain but easy-to-see phenomenon with a simple example. I have spent the last couple of months creating a fairly straightforward Windows application that is intended to store and retrieve data from a database, as well as perform some calculations on that data using Visual Studio Tools for Office and an Excel spreadsheet back end. For unit testing the calculations and the Excel back end, I have simply hard-coded specific data into my unit tests, which have exercised all of the spreadsheet's various functions. This has worked well and my unit tests are serving their purpose wonderfully.

For the database interactions, however, I have faced some difficult issues in creating appropriate unit tests. On one hand I have a frequently changing data model. This breaks my unit tests a lot but, on the whole, this is fine because I would specifically like my unit tests to alert me to breaking changes in the database structure.

On the other hand, many of my unit tests are not specifically testing database interactions, but instead test functionality, which is so complex that it is highly dependent upon the data that happens to be in the database and its structure. As a result, when the data in the database changes, my unit tests - which are expecting results that are specific to the state of the data when they were written - break. I then have to go in, examine the failed assertions, and change them to match the new data in the database. Eventually, the data changes again and they fail again.

Enter Mock Objects
I have been familiar with mock objects for several years. I've realized that they could provide solutions to my problems. However, at my former employer, there was a developer who used to spend hours, days, and even weeks creating elaborate mock infrastructures to have perfect unit tests - often at the cost of actually shipping software on time. Having seen this I, of course, was none-too-enthusiastic about mock objects.

Then, a colleague at Magenic posted to our internal technical lists about NMock. NMock, it seemed, held the potential to allow me to create mock objects to solve my problems without having to spend lots of time in their creation. "Cool," thought I.

Thus, the first thing to understand about NMock is that it is free. Well, the license says that you have to keep the copyright notice, but it looks to me (though I am not a lawyer) as though you can redistribute it and use it in various other products, including commercial ones, so I would call that free.

The second thing to understand is that NMock creates mock objects at run time, rather than doing pre-generation. This went against the way I had envisioned a mock object generator would work before I had ever seen one, so I was a little surprised by this. The creators say that this makes mock objects created with NMock more resilient and avoids a pre-usage compilation step. I guess I can see that.

Taking It for a Test Drive
Therefore, for my first crack at using mock objects, I decided to choose one of my existing unit tests that had been breaking. The test had to do with authorization of users into my system. It was intended to find a user in the database, retrieve a number of facts about that user, and then assert that those facts matched the facts of which I have a priori knowledge.


[TestFixture]
public class UserTest
{
[Test]
public void VerifyRoleRetrieval()
{
User user = new User();
user.Authorize("derek");

Assert.AreEqual(5, user.Roles.Count);
}
}
As you see in the above test, I begin by creating a new User object. I then call "Authorize" on the object, which causes it to populate itself with data about the requested user (in this case, myself). Finally, I assert that the number of roles associated with my own user account is five, because I know in advance that that is how many roles will be on the user object, if the population has been correctly done.

Unfortunately, as you may have guessed, the number of roles associated with my account on our system varied continually during development, which made this test difficult to maintain, at best. Once the system went into production it wasn't quite as bad, but it still wasn't ideal.


public class User
{
ArrayList roles;

public void Authorize()
{
ArrayList roles = new ArrayList();
// IP for populating roles removed here
}

public ArrayList Roles
{
get
{
return roles;
}
}
}
The code above shows - more or less - what happens inside of the User class to make the authorization and role-recollection functionality work. I had to remove some code from the Authorize method to protect my client's Intellectual Property but, nevertheless, you can see that a simple ArrayList is used to contain the roles. The code I removed was tied too closely to an actual database, thus making it difficult to unit test.

Following the approach documented right on NMock's home page, I adapted my user class to take a reference to an "Authorizer" class. The Authorizer class would contain my DB logic in the real application, but in my unit tests, it is what will be mocked. For this reason I have declared it as an interface in Listing 1, which different classes can implement depending upon the circumstances (test or production).

The code in Listing 2 shows my first cut at amending my tests to use an automatically generated unit test. This compiled and ran but, unfortunately, it did not pass since there is nothing to tell NMock to actually return an ArrayList with five members as a part of this test.

Listing 3 shows the modifications I had to make in order to finally build a good unit test for my User class's Authorization functionality. In my unit test I had to create an artificial unit test for my User class to return. I then had to change my call to the "Expect" method on the dynamically generated mock to be "ExpectAndReturn," passing in the value for it to return, in addition to my expectations about the way that the Authorize method should be called.

The Authorize method populates the internal roles variable in the User class so that a little Assert test that expects five members will succeed.

Conclusion
My conclusion after using NMock for about an hour is that it is definitely a good way to help create unit tests that will serve well beyond the initial creation of your code. My other realization was that in some ways, seeing that your code requires re-architecture in order to support easy mocking can be an indication that one hasn't architected one's initial code with the greatest possible degree of flexibility, to begin with.

I anticipate adding NMock to my bag of tricks and using it extensively going forward. To read about my further experiences with unit testing, please read my blog at http://derek.dotnetdevelopersjournal.com/.

More Stories By Derek Ferguson

Derek Ferguson, founding editor and editor-in-chief of .Net Developer's Journal, is a noted technology expert and former Microsoft MVP.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...