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:

/// <summary>
/// Implementation of the mail sender service.
/// </summary>
public class MailSenderService
{
/// <summary>
/// Sends the mail using the specified options.
/// </summary>
/// <param name="mail">The mail.</param>
/// <param name="mailOptions">The mail options.</param>
public void SendMail(Mail mail, MailOptions mailOptions)
{
SmtpClient client = new SmtpClient();
if (mailOptions.SaveToFile)
{
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = mailOptions.FilePath;
}
client.Send(mail.GetMailMessage());
Trace.TraceInformation("Send mail successfully with subject : '{0}' from '{1}'.".FormatWith(mail.Subject, mail.FromAddress.Address));
}
}

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

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
<Assembly Name="System" Version="4.0.0.0"/>
<ShimGeneration>
<Add TypeName="SmtpClient"/>
</ShimGeneration>
</Fakes>
view raw System.fakes hosted with ❤ by GitHub

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

[Test]
public void Mail_ShouldBeSend_When_SendMailWasCalled()
{
//Arrange
bool sendMailwasCalled = false;
var mail = new Mail();
mail.FromAddress = new MailAdres("John Doe", "john@doe.be");
mail.ToAddress.Add(new MailAdres("jane@doe.be"));
mail.Body = new MailBody() { Body = "test", IsHtml = false };
mail.Subject = "test mail";
var mailOptions = new MailOptions();
//Continue with the act & assert 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:

//Act
using (ShimsContext.Create())
{
// Arrange:
System.Net.Mail.Fakes.ShimSmtpClient.AllInstances.SendMailMessage =
(client, message) => sendMailwasCalled = true;
var service = new MailSenderService();
service.SendMail(mail, mailOptions);
}
//Assert
Assert.IsTrue(sendMailwasCalled);

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

Popular posts from this blog

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

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.

.NET 9 - Goodbye sln!

Although the csproj file evolved and simplified a lot over time, the Visual Studio solution file (.sln) remained an ugly file format full of magic GUIDs. With the latest .NET 9 SDK(9.0.200), we finally got an alternative; a new XML-based solution file(.slnx) got introduced in preview. So say goodbye to this ugly sln file: And meet his better looking slnx brother instead: To use this feature we first have to enable it: Go to Tools -> Options -> Environment -> Preview Features Check the checkbox next to Use Solution File Persistence Model Now we can migrate an existing sln file to slnx using the following command: dotnet sln migrate AICalculator.sln .slnx file D:\Projects\Test\AICalculator\AICalculator.slnx generated. Or create a new Visual Studio solution using the slnx format: dotnet new sln --format slnx The template "Solution File" was created successfully. The new format is not yet recognized by VSCode but it does work in Jetbr...