Microsoft Fakes and Plugin

Just sharing the helper class we use for writing Unit Test for Plugin using Microsoft Fakes

Sample Code for Plugin

public class PluginClass: IPlugin
public void Execute(IServiceProvider serviceProvider)
IPluginExecutionContext context =

// Everytime a lead record is created
// Create a corresponding contact record

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
Entity entity = (Entity)context.InputParameters["Target"];

IOrganizationServiceFactory serviceFactory =

IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);

if (entity.LogicalName == "lead")
Entity contactEntity = new Entity("contact");
contactEntity.Attributes["lastname"] = entity.Attributes["subject"];

Sample Code for Unit Test Class

public class UnitTest1
public void UnitTestMethod()
var serviceProvider = new StubIServiceProvider();
var pluginContext = new StubIPluginExecutionContext();
var organizationService = new StubIOrganizationService();

// Mole the basic Plugin objects
Helper.FakePluginVariables(serviceProvider, pluginContext, organizationService, 40, "Create");

// set the mole of entity
var entityAttributes = new Dictionary<string, object>();

entityAttributes.Add("subject", "Test Subject");
Entity leadEntity = Helper.FakeEntity("lead", entityAttributes, pluginContext);

// set the entity in the parameter collection
var parameterAttributes = new Dictionary<string, object>();
parameterAttributes.Add("Target", leadEntity);
Helper.FakePluginInputParameters(pluginContext, parameterAttributes);

organizationService.CreateEntity = (p1) => { return Guid.NewGuid(); };

var postCreateLead = new Class1();

Helper class

/// <summary>
/// Helper class for Fakes
/// </summary>
public static class Helper
/// <summary>
/// Fakes the plugin variables.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <param name="pluginContext">The plugin context.</param>
/// <param name="organizationService">The organization service.</param>
/// <param name="stageNumber">The stage number.</param>
/// <param name="messageName">Name of the message.</param>
public static void FakePluginVariables(
StubIServiceProvider serviceProvider,
StubIPluginExecutionContext pluginContext,
StubIOrganizationService organizationService,
int stageNumber,
string messageName)
var serviceFactory = new StubIOrganizationServiceFactory();
var tracingService = new StubITracingService();
if (serviceProvider != null)
serviceProvider.GetServiceType = type =>
if (type == typeof(IPluginExecutionContext))
return pluginContext;
else if (type == typeof(ITracingService))
return tracingService;
else if (type == typeof(IOrganizationServiceFactory))
return serviceFactory;

return null;

pluginContext.DepthGet = () => 1;
pluginContext.UserIdGet = () => new Guid();
pluginContext.MessageNameGet = () => messageName;
pluginContext.StageGet = () => stageNumber;
pluginContext.InitiatingUserIdGet = () => new Guid();
pluginContext.CorrelationIdGet = () => new Guid();
pluginContext.PrimaryEntityIdGet = Guid.NewGuid;
serviceFactory.CreateOrganizationServiceNullableOfGuid = t1 => organizationService;
tracingService.TraceStringObjectArray = Trace;

/// <summary>
/// Sets the Fakes for the Entity
/// </summary>
/// <param name="entityName">The LogicalName of the entity</param>
/// <param name="attributeValues">The attributes of the entity</param>
/// <param name="context">Object of type SIPluginExecutionContext</param>
/// <returns>Object of type Entity</returns>
public static Entity FakeEntity(string entityName, Dictionary<string, object> attributeValues, StubIPluginExecutionContext context)
var entity = new Entity(entityName);
entity.Attributes = new AttributeCollection();

if (attributeValues != null)
foreach (string key in attributeValues.Keys)
entity.Attributes.Add(key, attributeValues[key]);

if (context != null)
context.PrimaryEntityNameGet = () => entityName;

entity.Id = Guid.NewGuid();

return entity;

/// <summary>
/// Fakes the PluginContext.InputParameters
/// </summary>
/// <param name="context">the mole of the IPluginExecutionContext</param>
/// <param name="inputParameterCollection">Object of type System.Dictionary</param>
public static void FakePluginInputParameters(StubIPluginExecutionContext context, Dictionary<string, object> inputParameterCollection)
if (inputParameterCollection != null)
var parameterCollection = new ParameterCollection();
foreach (var key in inputParameterCollection.Keys)
parameterCollection.Add(key, inputParameterCollection[key]);

if (context != null)
context.InputParametersGet = () => parameterCollection;

/// <summary>
/// Detour method for the CRM Trace method
/// </summary>
/// <param name="content">the message to be traced</param>
/// <param name="value">Object of type object []</param>
public static void Trace(string content, params object[] value)


// Update 
   organizationService.UpdateEntity = (p) =>

// Execute
  organizationService.ExecuteOrganizationRequest = orgReq =>
                    return new OrganizationResponse();

// Retrieve
 organizationService.RetrieveStringGuidColumnSet = (p1, p2, p3) =>
                Entity entity = null;
                if (p1 == entity1.EntityLogicalName)
                    entity = new Entity(entity1.EntityLogicalName);
                    entity.Id = Guid.NewGuid();
                    entity.Attributes["new_category"] = new OptionSetValue(12345);
                    entity.FormattedValues["new_category"] = "home";                   
                else if (p1 == entity2.EntityLogicalName)
                    entity = new Entity(entity2.EntityLogicalName);
                    entity.Id = Guid.NewGuid();
                    entity.Attributes["new_moneyattr"] = new Money(100.0M);                    
                return entity;
  organizationService.RetrieveMultipleQueryBase = delegate(QueryBase query)
                var collection = new EntityCollection();
                Entity entity;
                if (query is FetchExpression)
                    entity = new Entity(entity.EntityLogicalName);
                    entity.Attributes = new AttributeCollection();
                    entity.Attributes.Add("attr", "value");                
                return collection;
// PreImage
  pluginContext.PreEntityImagesGet = () =>
                EntityImageCollection entityImgColl = new EntityImageCollection();
                Entity preImageEntity = new Entity(enitity1.EntityLogicalName);         
                preImageEntity.Attributes.Add("new_id", new EntityReference(entity2.EntityLogicalName, Guid.NewGuid()));
                preImageEntity.Attributes.Add("new_bool", false);
                KeyValuePair<string, Entity> kvp = new KeyValuePair<string, Entity>("PreImageAI", preImageEntity);
                return entityImgColl;



Hope it helps

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

2 thoughts on “Microsoft Fakes and Plugin”

Please share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CRM for You and Me

Customer Relationship Mgt App for the Professional

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform


Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions


Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

Two Bite Tips

Valuable Tips To Grow Your Business

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM


Mail to for queries and suggestions

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM


Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

Sara Lagerquist

No Code Customization Concepts


developer, designer, writer, fun loving, patriotic, humble and a sweet person inside out :) love and respect people who have a great sense of humor.

Temmy Wahyu Raharjo

Dreaming to be a clean coder and TDD minded programmer.

Transform 365

We blog about problems we face and code we write to help others

%d bloggers like this: