Unit testing CRM 2011 plugins. Approaches - Part 1

Today I want to describe two possible ways to unit test plugins. I will explain advantages and disadvantages of approaches.

I’m going to unit test a plugin which creates a task to call a lead in two weeks after lead creation. MS Test will be used as unit testing framework.

First of all let me give you overview of the Visual Studio solution. It consists of three projects:

HowTo.Logic – Class library. Contains business logic.
HowTo.SimplePlugin – Class library. Contains plugins.
HowTo.Tests – Test Project.

Now I want to list a code to clarify what is inside the projects.

The main method (CreateTaskToCall) of HowTo.Logic project listed below. It creates task based on provided lead:

And of corse let's take a look on Execute method of the plugin. Plugin just calls CreateTaskToCall and passes newly created lead and service to this method.

As mentioned there are two ways to test the code I listed. We can test business logic or we can test whole plugin.

Business logic testing

This approach covers business logic only and tests only method (CreateTaskToCall in our case) which is used in the plugin. For this approach you should avoid plugin being registered because same logic will be executed twice.

The main advantage of this approach shows up during development because you don’t need to redeploy plugin after each change in the logic. You can also debug you logic without attaching to process as it always happens when you debugging plugins.

Plugin testing

The idea is to trigger registered plugin and then check results. This approach allows us to test all aspects of the plugin not only business logic it executes. Moreover it allows checking if any other plugins affect results of plugin we are testing.

I use first approach during plugin development but switch to second when I finish with debugging.

In part 2 you can find two more approaches.

Good luck with the testing :)

You can download Visual Studio project here: