Unit Testing Dynamics CRM Plugins

There is no Spoon CRM

The purpose of this post will be to look at the code for a fairly typical looking crm plugin, and examine how to implement a unit test with the least possible effort. Reduced Effort == Reduced Person Hours == Reduced Cost.

Remember, this is Unit Testing, not Integration testing - so at test time - there is no CRM!

A plugin - and it’s requirements

Firstly, let’s look at a plugin that we will call the ReclaimCreditPlugin. Here are the requirements:

  • It must run only within a transaction with the database.
  • When a Contact entity is Updated, if the contact has a parent account, and that parent account is “on hold” then set the “taketheirshoes” flag on the contact record to true.

Developer Jon Doe

Jon Doe immediately gets to work on writing the plugin for those requirements. He produces the following plugin:

 1    public class ReclaimCreditPlugin : IPlugin
 2    {
 4        public void Execute(IServiceProvider serviceProvider)
 5        {
 7            var executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
 9            // 1. We must run only within a transaction
10            if (!executionContext.IsInTransaction)
11            {
12                throw new InvalidPluginExecutionException("The plugin detected that it was not running within a database transaction. The plugin requires a database transaction.");
13            }
15            // 2. Get the contact, check its parent account.
16            if (executionContext.InputParameters.Contains("Target") && executionContext.InputParameters["Target"] is Entity)
17            {
18                // Obtain the target entity from the input parameters.
19                var contactEntity = (Entity)executionContext.InputParameters["Target"];
20                // Get the parent account id.
21                var parentAccountId = (EntityReference)contactEntity["parentaccountid"];
23                // Get the parent account entity.
24                var orgServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
25                var orgService = orgServiceFactory.CreateOrganizationService(executionContext.UserId);
26                var parentAccountEntity = orgService.Retrieve("account", parentAccountId.Id, new ColumnSet("creditonhold"));
28                var accountOnHold = (bool)parentAccountEntity["creditonhold"];
30                if (accountOnHold)
31                {
32                    contactEntity["taketheirshoes"] = true;
33                    var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
34                    tracingService.Trace("Have indicated that we should take the shoes from contact: {0}", contactEntity.Id.ToString());
35                }
37            }
39        }
41    }

Good Job?

Take a moment to peer review the above code. Would you vindicate Jon Doe’s effort? It seems it has all the required logic in all the required places. It appears he has covered the list of requirements. Although Jon doesn’t check to make sure the current entity being updated is definately a contact entity.. But within the confines of this blog post we will assume that there is no possible danger that the plugin could ever be registered against the wrong entity.

So.. does it actually work?

Does it work?

Assuming you want to start haemorrhaging people’s time accross the organisation, one way to find out if this code works is to immediately go through the process of deploying it to a QA environment, getting someone to test it manually, and then repeating that cycle of Dev –> Deployment –> QA as often as necessary, until the tester gives the thumbs up.

If you want to go that route, feel free to skip the rest of this article. Otherwise read on, where sanity awaits!

Show me a Unit Test Already!

Bad news for you. I could.. but I won’t.

Why won’t you show me a unit test?

In short, because I value my time. Just look at that code again for crying out loud! It’s littered with dependencies on things that are only provided at runtime by Dynamics CRM - things like:

  • IServiceProvider
  • IPluginExecutionContext
  • IOrganizationServiceFactory
  • IOrganizationService
  • ITracingService


Listen.. I read those requirements for this plugin. I read them atleast one thousand times. And I wrote them in fact. Here they are again:

  • It must run only within a transaction with the database.
  • When a Contact entity is Updated, if the contact has a parent account, and that parent account is “on hold” then set the “taketheirshoes” flag on the contact record to true.

So with that in mind, can you please show me the requirement dictating: When a contact is updated, it is of upmost importance to us as a business that it looks at theIPluginExecutionContextand grabs theIOrganizationServiceFactory.`

Or please show me where the requirements state: When a contact is updated, the plugin absolutely must interact with theIServiceProvider` because otherwise you know.. Our business just won’t function anymore.

No my friends. The requirements do not say any of that. I am in the business of testing against the requirements.

Why is that a problem?

The problem is not obvious at first glance. It is definately technically possible to mock / fake all of those services at unit test time. You can use something like RhinoMocks or another Mocking library to mock out IServiceProvider for the purposes of your test. You would then have to mock out all the calls to IServiceProvider that are made, so that it returns your other ‘mocked’ services like a mock ‘IPluginExecutionContext’ etc etc - and down the rabbit hole you go.

The problem, is about effort. This approach, although technically possible, requires significant effort. You would have to mock a tonne of runtime services and interactions. We have to ask ourselves, is all that effort really necessary? Sometimes it may be, but most of the time, it isn’t. In this instance it definately isn’t and I will explain why.

Let’s use the requirements to write the plugin, in pseudo code.

With those requirements - forget everything you know about Dynamics Crm and write your ideal pseudo code that would implement those requirements. This is the actual logic we care about testing.


 1if (!IsRunningInTransaction)
 3	Throw "Plugin requires a transaction."
 6If (IsUpdateOf("contact"))
 9var contact = GetTargetEntity();
10var account = GetAccountForContact(contact);
12var isOnHold = (bool)account["creditonhold"];
15 	contact["taketheirshoes"] = true;

Look at that Pseudo Code - Do you see any runtime services?

Notice how it contains only the logic we really care about testing - the logic as described by the requirements. It doesn’t contain needless fluff. No IServiceProvider, No IPluginExecutionContext. It looks very simple, very basic. If we could actually write a CRM plugin like this, it would be about 1.5 million times easier to test. Well we can.

Isolating out dependencies is the key to unit testing.

Yes it’s true folks you heard it here first. The less dependencies you utilise directly in your methods, the easier they are to unit test.

With this principle in mind, let’s revisit our plugin and refactor it to remove some dependencies.

New and Improved Plugin

 1 public class ReclaimCreditPlugin2 : IPlugin
 2    {
 4        private IServiceProvider _ServiceProvider;
 6        public void Execute(IServiceProvider serviceProvider)
 7        {
 8            _ServiceProvider = serviceProvider;
 9            Execute();
10        }
12        /// <summary>
13        /// This is the method containing the business logic that we want to be able to assert at unit test time.
14        /// </summary>
15        public void Execute()
16        {
17            // 1. We must run only within a transaction
18            if (IsInTransaction())
19            {
20                throw new InvalidPluginExecutionException("The plugin detected that it was not running within a database transaction. The plugin requires a database transaction.");
21            }
23            // 2. Get the contact
24            var contact = GetTargetEntity();
26            // 3. Get the Parent Account for the contact.
27            var parentAccount = GetAccountEntity(contact);
28            if (parentAccount == null)
29            {
30                return;
31            }
33            // 4. If credit on hold, set taketheirshoes.
34            var accountOnHold = (bool)parentAccount["creditonhold"];
35            if (accountOnHold)
36            {
37                contact["taketheirshoes"] = true;
38            }
40        }
42        /// <summary>
43        /// Returns the parent account entity for the contact.
44        /// </summary>
45        /// <param name="contact"></param>
46        /// <returns></returns>
47        protected virtual Entity GetAccountEntity(Entity contact)
48        {
49            // Get the p[arent account id.
50            var parentAccountId = (EntityReference)contact["parentaccountid"];
52            // Get an instance of the IOrganisationService.
53            var orgServiceFactory = (IOrganizationServiceFactory)_ServiceProvider.GetService(typeof(IOrganizationServiceFactory));
54            var executionContext = (IPluginExecutionContext)_ServiceProvider.GetService(typeof(IPluginExecutionContext));
55            var orgService = orgServiceFactory.CreateOrganizationService(executionContext.UserId);
57            // Get the account entity, with only the column / attribute that we need.
58            var parentAccountEntity = orgService.Retrieve("account", parentAccountId.Id, new ColumnSet("creditonhold"));
59            return parentAccountEntity;
60        }
62        /// <summary>
63        /// Returns the current "Target" entity that the plugin is executing against.
64        /// </summary>
65        /// <returns></returns>
66        protected virtual Entity GetTargetEntity()
67        {
68            var context = (IPluginExecutionContext)_ServiceProvider.GetService(typeof(IPluginExecutionContext));
69            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
70            {
71                var contactEntity = (Entity)context.InputParameters["Target"];
72                return contactEntity;
73            }
75            return null;
76        }
78        /// <summary>
79        /// Returns whether the plugin is currently enrolled within a database transaction.
80        /// </summary>
81        /// <returns></returns>
82        protected virtual bool IsInTransaction()
83        {
84            var context = (IPluginExecutionContext)_ServiceProvider.GetService(typeof(IPluginExecutionContext));
85            return context.IsInTransaction;
86        }
88    }

What just happened?

I applied a technique called the Extract and Override technique, to remove the concrete references to all of those CRM runtime only services from within the Execute method, and instead they are now referenced within virtual methods which can be overriden at unit test time.

For example rather than having the following code directly within the execute method:

1  var executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
3            // 1. We must run only within a transaction
4            if (!executionContext.IsInTransaction)
5            {

It has been replaced by a call to virtual method:

1  	        if (IsInTransaction())
2            {
4            }

Because the interactions with the various CRM runtime Services now occur within Virtual methods, we no longer need to mock them up at unit test time. Say goodbye to having to mockup IPluginExecutionContext, IServiceProvider or any of the Crm runtime services. All we need to do now is just override the various virtual methods that our Execute() method calls, and return appropriate values at test time.

Ok so - Now will you show me a Unit Test??

Certainly Sir / Madame. Now that I can write one within a few minutes as opposed to a few hours, your wish is my command:-

For the purpose of our unit tests all we do, is create a class that derives from our original plugin class, but overrides the various virtual methods to provide different values at test time.

 1 public class UnitTestableReclaimCreditPlugin : ReclaimCreditPlugin2
 2    {
 4        public UnitTestableReclaimCreditPlugin()
 5        {
 6            AccountIsOnHold = false;
 7            IsRunningInTransaction = false;
 8            ContactEntity = new Entity("contact");
 9        }
11        protected override Entity GetTargetEntity()
12        {
13            ContactEntity["parentaccountid"] = new EntityReference("account", Guid.NewGuid());
14            return ContactEntity;
15        }
17        protected override Entity GetAccountEntity(Entity contact)
18        {
19            var accountEntity = new Entity("account");
20            accountEntity["creditonhold"] = AccountIsOnHold;
21            return accountEntity;
22        }
24        protected override bool IsInTransaction()
25        {
26            return IsRunningInTransaction;
27        }
29        public bool AccountIsOnHold { get; set; }
31        public bool IsRunningInTransaction { get; set; }
33        public Entity ContactEntity { get; set; }
35    }

And here are the Unit Tests

 1    [TestFixture]
 2    public class ReclaimCreditPluginUnitTests
 3    {
 4        public ReclaimCreditPluginUnitTests()
 5        {
 7        }
 9        [ExpectedException(typeof(InvalidPluginExecutionException),
10            ExpectedMessage = "The plugin detected that it was not running within a database transaction",
11            MatchType = MessageMatch.Contains)]
12        public void Should_Only_Run_Within_Transaction()
13        {
14            // arrange
15            var sut = new UnitTestableReclaimCreditPlugin();
16            sut.IsRunningInTransaction = false;
18            // act 
19            sut.Execute();
21        }
24        public void Should_Take_Shoes_When_Credit_On_Hold()
25        {
26            // arrange
27            var sut = new UnitTestableReclaimCreditPlugin();
28            sut.IsRunningInTransaction = true;
29            sut.AccountIsOnHold = true;
31            // act 
32            sut.Execute();
34            //assert
35            Assert.That(sut.ContactEntity["taketheirshoes"], Is.EqualTo(true));
37        }
39        public void Should_Not_Take_Shoes_When_Credit_Not_On_Hold()
40        {
41            // arrange
42            var sut = new UnitTestableReclaimCreditPlugin();
43            sut.IsRunningInTransaction = true;
44            sut.AccountIsOnHold = false;
46            // act 
47            sut.Execute();
49            //assert
50            Assert.That(sut.ContactEntity["taketheirshoes"], Is.Not.EqualTo(true));
52        }
53    }

Wrapping Up

I hope I have demonstrated a simple plugin, with a simple set of unit tests. More importantly, I hope I have demonstrated that although it may be technically possible to write a unit test for an exising plugin, by mocking up every CRM runtime service and interaction that the plugin makes,just because such a thing is possible, doesn’t mean you should just do it. First the work has to be justified. To justify just what is necessary, examine the requirements, examine the plugin code, and be absolutely clear on what it is you want to cover in your unit tests. With that in mind, refactor the plugin code to eliminate fluff (extraneoues concrete references to dependencies that are surplus to the requirements that you want to test). Use techniques like the Extract and Override technique to allow you to substitute these dependencies easily at test time. When you do this, you may be surprised at how much simpler it becomes to write unit tests. I would aslo reccommend reading a book on unit testing, I found The Art of Unit Testing very educational on this topic.

comments powered by Disqus