Month: May 2014

Fakes and Shims Generic Methods

Working with Microsoft’s Fakes and Shims is really a treat. I love how easy they are to setup and how I can be sure that I can test anything I need.

Problem:

Lately I have been trying to test Generic Methods of an Interface. Doesn’t seem like a challenge, as nothing else in the framework is, however I quickly found out it wasn’t as simple as I thought.

Take this interface as an example:

Pubic interface ISampleInterface
{
T GetMySample<T>();
}

When you add the Fakes and Shims Assembly, a class will be generated to allow you to apply functions to each of the interface members. However, you will notice the expected member is missing. Instead, you will get something that looks like the following:

fakes-shims-1

 

The issue is because of the Generic type in the interfaces member definition. The stubs don’t know what method type to create for you. It could try and generate a method for every implementation of T, but that seems to be a bit much.

Solution:

Instead, they give you a way of defining the type after the creation of the stub. You will see a new method on the stub called GetMySampleOf1. This is the method you will use to a give a definition to the generic method. Implementation of the stub will look like the following:

fakes-shims-2

You can see that I have implemented the interface for 4 different data types. String, Integer, Boolean, and DateTime. This makes it really easy to implement interface members with generic type arguments.

  • Dan
  • McCrady