Skip to main content

Visual Studio 2012: Testing the untestable using Microsoft Fakes

Testing the untestable

To test your code in isolation, Mocking frameworks like RhinoMocks or Moq are an important tool in your toolbox. By using an isolation(mocking) tool, you can replace an existing object by a ‘fake’ implementation. Unfortunately these tools cannot help you solve everything. If your system is not designed with testing in mind, it can be very hard or even impossible to replace an existing implementation with a mock object. Let’s for example take DateTime.Now.  This is a static property on a static class, how are you going to replace this?

Let’s have a look how Microsoft Fakes, the isolation framework that Microsoft introduced in Visual Studio 2012.

Microsoft Fakes

Microsoft Fakes help you isolate the code you are testing by replacing other parts of the application with stubs or shims.

  • A stub replaces another class with a small substitute that implements the same interface. To use stubs, you have to design your application so that each component depends only on interfaces, and not on other components.So this is similar to the functionality that most other mocking frameworks offer.

  • A shim modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims can be used to replace calls to assemblies that you cannot modify, such as .NET assemblies.(It is using the Moles Isolation Framework behind the scenes)

Fakes replace other components

So what does this mean? By using the ‘shims’ we can isolate any kind of functionality inside our .NET application, including non-virtual and static methods in sealed types. No longer we are limited to to interfaces or virtual methods to replace dependencies.

Remark: Using Shims has a performance impact on your tests because it will rewrite your code at run time.

How to use Microsoft Fakes?

Let’s walk through an example. In this sample I want to test the SmtpClient, preferably without sending real emails. Below you’ll find the MailService class I want to test. This class has a direct dependency on the SmtpClient making it hard to test:

The SmtpClient class lives in the System assembly. To create a shim for this class,  go to the Test Project, right-click on the System assembly in the references for the project, and choose “Add Fakes Assembly”:

image

This creates a System.fakes file within the project:

image

It also creates a Fakes folder containing a .fakes file for every fakes assembly we created:

image

Inside the System.fakes file, we can specify for which types a shim should be created(for some types, this is done by default):

Let’s now write our test. Start by creating the test method and specifying the ‘arrange’ part:

Now we continue by adding the ‘act’ and ‘assert’ part of our tests. Because we want to use shims, we’ll have to wrap our calls into a special ShimsContext. The Microsoft Fakes framework created a ShimSmtpClient in the System.Net.Mail.Fakes namespace. On this ShimSmtpClient, we can overwrite the SendMailMessage method of all SmtpClient implementations through the Action<SmtpClient,MailMessage> property available on the AllInstances property:

This naming convention is used for all shims you create in your test application.

Popular posts from this blog

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

Kubernetes–Limit your environmental impact

Reducing the carbon footprint and CO2 emission of our (cloud) workloads, is a responsibility of all of us. If you are running a Kubernetes cluster, have a look at Kube-Green . kube-green is a simple Kubernetes operator that automatically shuts down (some of) your pods when you don't need them. A single pod produces about 11 Kg CO2eq per year( here the calculation). Reason enough to give it a try! Installing kube-green in your cluster The easiest way to install the operator in your cluster is through kubectl. We first need to install a cert-manager: kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.5/cert-manager.yaml Remark: Wait a minute before you continue as it can take some time before the cert-manager is up & running inside your cluster. Now we can install the kube-green operator: kubectl apply -f https://github.com/kube-green/kube-green/releases/latest/download/kube-green.yaml Now in the namespace where we want t...

DevToys–A swiss army knife for developers

As a developer there are a lot of small tasks you need to do as part of your coding, debugging and testing activities.  DevToys is an offline windows app that tries to help you with these tasks. Instead of using different websites you get a fully offline experience offering help for a large list of tasks. Many tools are available. Here is the current list: Converters JSON <> YAML Timestamp Number Base Cron Parser Encoders / Decoders HTML URL Base64 Text & Image GZip JWT Decoder Formatters JSON SQL XML Generators Hash (MD5, SHA1, SHA256, SHA512) UUID 1 and 4 Lorem Ipsum Checksum Text Escape / Unescape Inspector & Case Converter Regex Tester Text Comparer XML Validator Markdown Preview Graphic Col...