Archive for September, 2004

22
Sep

NMock To The Rescue

I was working with Drew today and preparing for our .Net Users Group presentation on leveraging open source development tools with .Net. For this presentation, we have consistently met at Panera because of the free wifi access. When we arrived this evening we were unable to connect to the wifi. At first, this seemed like a pretty big problem, but it ended up being a perfect scenario for how mock objects can provide a significant advantage..

My pieces of the presentations are centered around NUnit and NMock. In the example code that we put together for the presentation, the data layer is comprised of an external (XMethods) web service. Without wifi, we were obviously unable to connect to the web service. The wonderful part about all of this was … it didn’t matter.

Since the tests in the business layer utilized the functionality of NMock, the tests all ran as expected. The only exception to this was the suite of integration tests, which confirmed that the service wasn’t available and that the integration tests were doing their job correctly.

So, even without the core service that we needed to talk to, Drew was able to setup NAnt scripts and get Cruise working with full unit test integration. We would have been able to do a portion of this work anyway, but we wouldn’t have been able to do any refactoring of the tests or code modifications with full confidence that the code was still functioning as we expected (the test would have all failed instead of passing).

There are a variety of scenarios where mock objects can be a wonderful addition to your toolset and development process. This scenario was a prime example. We didn’t control the internet connection at Panera, but it wasn’t able to stop us from moving forward and preparing the presentation or performing the integration of the code and various toolsets.

A couple of other places where mocks (implemented correctly) can save the day include:

  • When your unit tests take a long time to run (the faster the feedback the better)
  • When systems are out of your control (that big mainframe app that goes down all the time)
  • When systems are not always available (when that big mainframe has to be rebooted every night and takes a couple of hours to get back up successfully)
  • When systems return dynamic results (such as stock prices, current temperature, the current election results, etc.)
  • When a system doesn’t exist yet (parallel development, etc.)

If you are interested in learning more about how to implement mock objects in .Net, take a look at this MSDN article. The article provides all you need to know to get started with NMock up and running.