Unit testing is essential for ensuring that your MS CRM plugins function correctly. FakeXrmEasy is a testing library designed specifically for Dynamics 365 (CRM) that simplifies the process of writing unit tests by allowing you to mock the CRM environment. This guide will walk you through the steps to write plugin unit tests using FakeXrmEasy.
Step 1: Set Up Your Development Environment
Before you start, ensure you have the following tools installed:
- Visual Studio: An integrated development environment (IDE) from Microsoft.
- MS CRM SDK: The Software Development Kit (SDK) for MS CRM.
- FakeXrmEasy: A library to facilitate unit testing in Dynamics 365.
Step 2: Create a New Project
- Open Visual Studio and create a new Class Library project for your plugin.
- Add References to the MS CRM SDK assemblies. Common assemblies include:
Microsoft.Xrm.Sdk.dll
Microsoft.Crm.Sdk.Proxy.dll
- Install FakeXrmEasy via NuGet Package Manager.
Step 3: Implement the Plugin Logic
Write your plugin logic if it is not already written. Here is a simple example of a plugin that updates a field on an account entity:
using Microsoft.Xrm.Sdk; // Import the CRM SDK namespace
// Define a plugin class that implements the IPlugin interface
public class UpdateAccountPlugin : IPlugin
{
// The Execute method is called when the plugin is executed
public void Execute(IServiceProvider serviceProvider)
{
// Retrieve the plugin execution context from the service provider
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Retrieve the organization service factory from the service provider
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
// Create an instance of the organization service using the current user's credentials
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// Check if the input parameters contain a target entity and if it is of type Entity
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Retrieve the target account entity from the input parameters
Entity account = (Entity)context.InputParameters["Target"];
// Update the description field of the account entity
account["description"] = "Updated by plugin";
// Save the changes to the account entity in the CRM
service.Update(account);
}
}
}
Step 4: Create Unit Test Project
- In Visual Studio, create a new “Class Library (.NET Framework)” project.
- Right-click the project in the Solution Explorer and select “Add” -> “New Item“.
- Choose “Unit Test (.NET Framework)” and name it appropriately (e.g.,
YourPluginTests
).
Install FakeXrmEasy:
- Use the NuGet Package Manager to install the FakeXrmEasy library that matches your Dynamics 365 version.
- Search for “FakeXrmEasy” and install the relevant package for your project.
Reference Your Plugin Project:
- Right-click on your test project in the Solution Explorer and select “Add Reference“.
- Choose “Projects” and locate your Dynamics 365 plugin project.
- Select the project and click “OK“.
Set Up the Test Class:
- Open the newly created test class file (e.g.,
YourPluginTests.cs
). - Add the necessary namespaces using directives:
Write a Unit Test Method:
- Define a test method with the
[TestMethod]
attribute. - Inside the method, follow these general steps:
a. Setup Mock Objects: Use FakeXrmEasy to create mock objects representing the plugin execution context and entity data. Configure the mock objects with expected values based on the plugin’s functionality being tested.
b. Execute the Plugin: Create an instance of your plugin class.- Call the
Execute
method of the plugin, passing the mock execution context object as a parameter.
c. Validate Results:- Assert the expected behavior of the plugin using assertions from the
Microsoft.VisualStudio.TestTools.UnitTesting
framework. - Verify if data was created, updated, or deleted as intended.
- Call the
Here’s an example unit test using FakeXrmEasy:
using Microsoft.VisualStudio.TestTools.UnitTesting; // Unit testing framework
using FakeXrmEasy; // FakeXrmEasy library for mocking CRM environment
using Microsoft.Xrm.Sdk; // CRM SDK
using System; // System namespace for basic functionalities
using YourPluginNamespace; // Namespace where your plugin is defined
namespace PluginUnitTest
{
[TestClass] // Attribute indicating this is a test class
public class UpdateAccountPluginTest
{
[TestMethod] // Attribute indicating this is a test method
public void Test_UpdateAccountPlugin_DescriptionUpdated()
{
// Arrange - setting up the test context and initial data
// Create a new instance of the XrmFakedContext
var context = new XrmFakedContext();
// Create a new account entity with a unique ID
var targetAccount = new Entity("account")
{
Id = Guid.NewGuid()
};
// Initialize the context with the target account entity
context.Initialize(new List<Entity> { targetAccount });
// Create a default plugin execution context and set the input parameters
var pluginContext = context.GetDefaultPluginContext();
pluginContext.InputParameters["Target"] = targetAccount;
// Instantiate the plugin to be tested
var plugin = new UpdateAccountPlugin();
// Act - executing the plugin with the prepared context
context.ExecutePluginWith<UpdateAccountPlugin>(pluginContext);
// Assert - verifying the results
// Retrieve the updated account entity from the context
var updatedAccount = context.CreateQuery("account").FirstOrDefault();
// Ensure the account entity is not null
Assert.IsNotNull(updatedAccount);
// Verify that the description field was updated by the plugin
Assert.AreEqual("Updated by plugin", updatedAccount["description"]);
}
}
}
Step 5: Run the Unit Tests
- Build the Solution to ensure there are no compilation errors.
- Run the Unit Tests using the Test Explorer in Visual Studio.
Step 6: Review and Refactor
After running the tests, review the results. If any tests fail, investigate the issues, correct the plugin code or test cases, and rerun the tests. Refactor your code to improve readability and maintainability.
Writing unit tests for MS CRM plugins using FakeXrmEasy makes the process more straightforward by providing a mock CRM environment. By following these steps, you can create a robust testing framework for your plugins, ensuring they work correctly and handle various scenarios effectively. Regular unit testing and continuous integration will help you catch issues early, reduce bugs, and maintain high-quality code in your Dynamics 365 environment.