Sticky

This blog has moved to www.dreamingincrm.com. Please update your feed Url. Thank you.

9 April 2014

Unit Testing Plugins using Microsoft Fakes

Plugin Registration tool's profiling functionality has made plugin debugging a lot easier. The ease of use can sometimes tempt you to use this feature in the early stages of plugin development, to analyse what is state of PluginExecutionContext, InputParameter, Pre/Post Images etc. This gives you an understanding of the plugin's flow and state, but only after it has been deployed to CRM. This, however, is not unit testing.

In this post, I will explain how easy it is unit test a plugin using Microsoft Fakes. In this post, I am using CRM 2013 Developer Toolkit for plugin development. If you are new to plugin development and would like to know how to use the developer toolkit to develop plugins refer to Ben Hosk's blog post http://crmbusiness.wordpress.com/2014/04/07/crm-2013-step-by-step-update-plugin-tutorial-using-the-crm-2013-development-toolkit/

What is Microsoft Fakes? 

It is a unit testing framework, that can be used to do isolation testing using Shims and Stubs.

How can I get it?

Microsoft Fakes comes free with Visual Studio Premium and Visual Studio Ultimate

What is the process?


  1. Create your plugin project and associated plugin boilerplate code (generated by developer toolkit)
  2. Create a unit test project
  3. Build your plugin project
  4. Add the following references to your unit test project
    1. Your plugin assembly
    2. Microsoft.Xrm.Sdk
    3. System
    4. System.Core
    5. System.Runtime.Serialization
  5. Right click on Microsoft.Xrm.Sdk in your unit test project and click on Add Fakes Assembly
  6. Right click on System in your unit test project and click on Add Fakes Assembly
After you have added all your references you project should look something like this



















Okay. Now what?

Now you can start writing your tests. To write an effective unit test you should start stubbing some classes in the Microsoft.Xrm.Sdk and overriding their behaviours. You have to use the following stubs inplace of their originals:
  1. StubIPluginExecutionContext
  2. StubITracingService
  3. StubIOrganizationService
  4. StubIServiceProvider

Scenario

You are developing a plugin which prevents the user from creating more than one opportunity for a customer.

Plugin Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnderstandingFakes
{
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;

    /// <summary>
    /// PreRegistrationPlugin Plugin.
    /// Fires when the following attributes are updated:
    /// All Attributes
    /// </summary>    
    public class PreOpportunityPlugin : Plugin
    {
        /// <summary>
        /// Alias of the image registered for the snapshot of the 
        /// primary entity's attributes before the core platform operation executes.
        /// </summary>
        private readonly string preImageAlias = "PreImage";

        /// <summary>
        /// Initializes a new instance of the <see cref="PreOpportunityPlugin"/> class.
        /// </summary>
        public PreOpportunityPlugin()
            : base(typeof(PreOpportunityPlugin))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "opportunity", this.ExecutePreCreateAndUpdate));
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "opportunity", this.ExecutePreCreateAndUpdate));

            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }

        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePreCreateAndUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            var context = localContext.PluginExecutionContext;
            Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;

            if (!context.InputParameters.Contains("Target"))
            {
                return;
            }
            var targetEntity = context.InputParameters["Target"] as Entity;
            var record = targetEntity;
            if (preImageEntity != null)
            {
                record = preImageEntity;
                foreach (var attribute in targetEntity.Attributes)
                {
                    record[attribute.Key] = targetEntity[attribute.Key];
                }
            }
            if (!record.Contains("customerid"))
            {
                return;
            }
            var customerLookup = record["customerid"] as EntityReference;
            var fetchOpportunities = string.Format(@" 
            <fetch version=""1.0"" outputformat=""xmlplatform"" mapping=""logical"" distinct=""false"" count=""50"">
             <entity name=""opportunity"">
              <attribute name=""opportunityid"" />
              <order attribute=""name"" descending=""false"" />
              <filter type=""and"">
               <condition attribute=""customerid"" operator=""eq"" value=""{0}"" />
              </filter>
             </entity>
            </fetch>", customerLookup.Id);
            var opportunitiesResult = localContext.OrganizationService.RetrieveMultiple(new FetchExpression(fetchOpportunities));
            if (opportunitiesResult.Entities.Count > 0)
            {
                throw new InvalidPluginExecutionException(string.Format("You cannot create more then one opportunity for this {0}", customerLookup.LogicalName == "account" ? "Account" : "Contact"));
            }
        }
    }
}

Test Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PluginTest
{
    using System.Diagnostics;
    using System.Fakes;

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Fakes;
    using Microsoft.Xrm.Sdk.Query;

    using UnderstandingFakes;

    [TestClass]
    public class PreOpportunityPluginUnitTests
    {
        private Entity TestEntity { get; set; }

        private static StubIServiceProvider ServiceProvider { get; set; }
        private static StubIPluginExecutionContext PluginExecutionContext { get; set; }
        private static StubIOrganizationService OrganizationService { get; set; }

        [ClassInitialize]
        public static void ClassInit(TestContext textContext)
        {
            var context = new StubIPluginExecutionContext();
            var tracingService = new StubITracingService();
            var orgFactory = new StubIOrganizationServiceFactory();

            ServiceProvider = new StubIServiceProvider();
            OrganizationService = new StubIOrganizationService();
            PluginExecutionContext = context;

            //override GetService behaviour and return our stubs
            ServiceProvider.GetServiceType =
                (type) =>
                {
                    if (type == typeof(IPluginExecutionContext))
                    {
                        return context;
                    }
                    else if (type == typeof(IOrganizationServiceFactory))
                    {
                        return orgFactory;
                    }
                    else if (type == typeof(ITracingService))
                    {
                        return tracingService;
                    }
                    return null;
                };
            context.UserIdGet = () => Guid.Empty;
            //return our stub organizationservice
            orgFactory.CreateOrganizationServiceNullableOfGuid = (userId) => OrganizationService;

            //write trace logs to output. only works when debugging tests
            tracingService.TraceStringObjectArray = (message, args) => Debug.WriteLine(message, args);
        }

        [TestInitialize]
        public void TestInit()
        {
            //setup initial values for each test
            var inputParameters = new ParameterCollection();
            PluginExecutionContext.InputParametersGet = () => inputParameters;
            TestEntity = new Entity();
            inputParameters.Add(new KeyValuePair("Target", TestEntity));
        }

        [TestCleanup]
        public void TestCleanup()
        {
            TestEntity = null;
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidPluginExecutionException), "Exception not thrown")]
        public void Must_Throw_Exception_When_More_Than_One_Opportunity()
        {
            PluginExecutionContext.StageGet = () => 20;
            PluginExecutionContext.MessageNameGet = () => "Create";
            PluginExecutionContext.PrimaryEntityNameGet = () => "opportunity";
            TestEntity["customerid"] = new EntityReference("contact", Guid.Empty);

            //setup retrievemultiple behavior to return three entities. we are ignoring the customerid
            //in the previous line
            OrganizationService.RetrieveMultipleQueryBase = (query) =>
            {
                var result = new EntityCollection();
                result.Entities.Add(new Entity());
                result.Entities.Add(new Entity());
                result.Entities.Add(new Entity());
                return result;
            };

            var plugin = new PreOpportunityPlugin();
            plugin.Execute(ServiceProvider);
        }

        [TestMethod]
        public void Must_Not_Throw_Exception_If_Only_No_Opportunities()
        {
            PluginExecutionContext.StageGet = () => 20;
            PluginExecutionContext.MessageNameGet = () => "Create";
            PluginExecutionContext.PrimaryEntityNameGet = () => "opportunity";
            TestEntity["customerid"] = new EntityReference("contact", Guid.Empty);

            //return no results
            OrganizationService.RetrieveMultipleQueryBase = (query) =>
            {
                var result = new EntityCollection();
                return result;
            };
            var plugin = new PreOpportunityPlugin();
            plugin.Execute(ServiceProvider);
        }

        [TestMethod]
        public void Must_Not_Throw_Exception_If_No_CustomerId()
        {
            PluginExecutionContext.StageGet = () => 20;
            PluginExecutionContext.MessageNameGet = () => "Create";
            PluginExecutionContext.PrimaryEntityNameGet = () => "opportunity";
            OrganizationService.RetrieveMultipleQueryBase = (query) =>
            {
                var result = new EntityCollection();
                result.Entities.Add(new Entity());
                return result;
            };
            var plugin = new PreOpportunityPlugin();
            plugin.Execute(ServiceProvider);
        }
    }
}

Where  can I find more information about Microsoft Fakes?

Refer to the content posted by Visual Studio ALM rangers in Codeplex https://vsartesttoolingguide.codeplex.com/releases/view/102290

This just barely scratches the surface of what is possible. Please explore the codeplex site to know more about how you can utilise Fakes in your CRM Development.

UPDATE: xRM Test Framework is my preferred choice for unit testing plugins and workflow assemblies these days -> https://xrmtestframework.codeplex.com/

No comments:

Post a Comment