Skip to content

February 4, 2013

Use a ‘Precision Mocker’ like Moq instead of a ‘Monster Mocker’ like Microsoft Fakes!

by adamstephensen

Using a precision mocking framework (such as Moq or NSubstitute) encourages developers to write maintainable, loosely coupled code.

Mocking frameworks allow you to replace a section of the code you are about to test, with an alternative piece of code.
For example, this allows you to test a method that performs a calculation and saves to the database, without actually requiring a database.

There are two types of mocking framework.

The Monster Mocker (e.g. Microsoft Fakes or TypeMock)

This type of mocking framework is very powerful and allows replacing code that wasn’t designed to be replaced.
This is great for testing legacy code (tightly coupled code with lots of static dependencies) and SharePoint.

Rule20130204-Image1
Rule20130204-Image2
Figure: Bad Example – Our class is tightly coupled to our authentication provider, and as we add each test we are adding *more* dependencies on this provider. This makes our codebase less and less maintainable. If we ever want to change our authentication provider “OAuthWebSecurity”, it will need to be changed in the controller, and every test that calls it.

The Precision Mocker (e.g. Moq)

This mocking framework takes advantage of well written, loosely coupled code.

The mocking framework creates substitute items to inject into the code under test.

Rule20130204-Image3Figure: Good Example – An interface describes the methods available on the provider

Rule20130204-Image4
Figure: Good Example – The authentication provider is injected into the class under test (preferably via the constructor) Rule20130204-Image5

Figure: Good Example – The code is loosely coupled. The controller is dependent on an interface, which is injected into the controller via its constructor. The unit test can easily create a mock object and substitute it for the dependency. Examples of this type of framework are Moq and NSubstitute.

Advertisements
Read more from Testing, Tools

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments