agentleFS
aidevmeaidevme/power-platform-claude-skills/dataverse-plugins-unit-testing/SKILL.md

dataverse-plugins-unit-testing

Skill2 starsChanged 8 months agoMITView on GitHub

Use when unit testing Dataverse plugins with FakeXrmEasy framework. Covers test setup, in-memory context, pipeline simulation, entity images, mocking, assertion patterns, bulk operations, file storage, async testing, CodeActivities, Azure Functions, custom messages, query testing, relationships, telemetry, and migration. Triggers on: "unit test plugin", "test plugin", "FakeXrmEasy", "plugin test", "mock context", "test IPlugin", "plugin unit testing", "fake context", "in-memory testing", "pipeline simulation test", "test execution context", "mock IOrganizationService", "test plugin images", "AAA pattern plugin", "test CodeActivity", "test Azure Function", "test custom API", "test FetchXML", "test QueryExpression", "test LINQ", "ILogger testing", "migrate FakeXrmEasy".

  • In this repositoryOne other file it gives its agents.

The file

Show its rules and text

We split this skill into the rules it gives an agent

13 rules. About 0 are common, 3 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use FakeXrmEasy for all plugin unit tests: Never use integration tests that require a live Dataverse connection when a unit test will …

    line 38
  2. Distinctive:

    Never recreate the context in every test method.

    line 45
  3. Very specific:

    Use Pipeline Simulation for integration-style plugin tests: When you need to test multiple plugins firing in sequence, use …

    line 50
  4. Very specific:

    Test negative cases and exception handling: Verify that plugins throw InvalidPluginExecutionException with the correct message when …

    line 57
  5. Very specific:

    Use early-bound entities when possible: Call _context.EnableProxyTypes(Assembly) to return strongly-typed entities from queries.

    line 60
  6. Very specific:

    Test bulk operations for performance-critical code: Use CreateMultipleRequest, UpdateMultipleRequest, and UpsertMultipleRequest …

    line 63
  7. Very specific:

    Every plugin unit test follows the Arrange-Act-Assert pattern.

    line 92
  8. Very specific:

    Use XrmFakedPluginExecutionContext directly — ExecutePluginWithTargetAndPreEntityImages is [Obsolete] in v2.6+:

    line 141
  9. Distinctive:

    Before writing any test code, read the plugin source and extract these signals:

    line 160
  10. Very specific:

    Throws: every throw InvalidPluginExecutionException needs 3 tests (happy, throws, message)

    line 166
  11. Very specific:

    Guards: every early return (entity guard, filtering attribute guard, depth guard) needs 1 test

    line 167
  12. Very specific:

    Create xUnit/NUnit/MSTest project targeting .NET Framework 4.6.2+ or .NET Core 3.1+

    line 175
  13. Very specific:

    Arrange: Create test data, configure XrmFakedPluginExecutionContext, set PreEntityImages

    line 209

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Dataverse Plugin Unit Testing Skill

You are an expert in writing unit tests for Dataverse plugins using the FakeXrmEasy framework. You create fast, isolated, in-memory tests that validate plugin logic without connecting to a real Dataverse environment. You understand the AAA (Arrange-Act-Assert) pattern, pipeline simulation, entity images, and how to mock complex plugin scenarios.

CRITICAL RULES

  1. Use FakeXrmEasy for all plugin unit tests. Never use integration tests that require a live Dataverse connection when a unit test will suffice. FakeXrmEasy provides an in-memory context that executes plugins against fake data.
  2. Always build the context via MiddlewareBuilder. FakeXrmEasyTestsBase does NOT exist in FakeXrmEasy v2.x or v3.x NuGet packages — do not reference it. Create _context once per class using MiddlewareBuilder.New().AddCrud().SetLicense(FakeXrmEasyLicense.RPL_1_5).Build(). Never recreate the context in every test method.
  3. Test plugins in isolation. Mock external dependencies. Don't make real HTTP calls, database connections, or file system operations in unit tests.
  4. Use Pipeline Simulation for integration-style plugin tests. When you need to test multiple plugins firing in sequence, use RegisterPluginStep and enable pipeline simulation.
  5. Assert against the Target entity reference for PreOperation changes. Plugins that modify Target in PreOperation don't call service.Update(). Assert against the same object reference you passed into the test.
  6. Test negative cases and exception handling. Verify that plugins throw InvalidPluginExecutionException with the correct message when validation fails.
  7. Use early-bound entities when possible. Call _context.EnableProxyTypes(Assembly) to return strongly-typed entities from queries. Makes tests more readable and catches type errors.
  8. Test bulk operations for performance-critical code. Use CreateMultipleRequest, UpdateMultipleRequest, and UpsertMultipleRequest (FakeXrmEasy 2.5+/3.5+) when processing multiple records. Bulk operations are Microsoft's recommended approach and can be 10x faster in production.

Quick Reference

ConceptFakeXrmEasy Approach
Install packageInstall-Package FakeXrmEasy.Plugins.v9 -Version 2.x (Framework) / 3.x (Core)
Build contextMiddlewareBuilder.New().AddCrud().SetLicense(FakeXrmEasyLicense.RPL_1_5).Build()
In-memory data_context.Initialize(new[] { account1, contact1 })
Execute plugin_context.ExecutePluginWith<MyPlugin>(pluginContext)
Execute (simple)_context.ExecutePluginWithTarget<MyPlugin>(target, "Create", 20)
Execute with PreImageBuild XrmFakedPluginExecutionContext with PreEntityImages set; call ExecutePluginWith<T>
Pipeline simulation_context.RegisterPluginStep<MyPlugin>("Create", stage)
Entity imagesRegister with PluginImageDefinition in RegisterPluginStep
Query results_context.CreateQuery<Account>().Where(a => a.Name == "test")
Mock dependenciesUse constructor injection or PluginInstance in registration
Bulk operationsCreateMultipleRequest, UpdateMultipleRequest, UpsertMultipleRequest (v2.5+/v3.5+)
File storageInitializeFileBlocksUploadRequest, DownloadFileRequest (v2.6+/v3.6+)
Async testingGetAsyncOrganizationService(), GetAsyncOrganizationService2() (v3.x only)
Custom APIsOrganizationRequest("new_CustomAPI"), test input/output parameters
RelationshipsAssociateRequest, DisassociateRequest, XrmFakedRelationship
CodeActivitiesExecuteCodeActivity<T>(activity, inputs) (requires separate package)
TelemetryMock ILogger<T>, verify log levels, structured logging
Migrationv1.x → v2.x/v3.x: MiddlewareBuilder, namespaces, SetLicense(RPL_1_5)

Test Anatomy (AAA Pattern)

Every plugin unit test follows the Arrange-Act-Assert pattern. Build _context once in the constructor via MiddlewareBuilder — FakeXrmEasyTestsBase does not exist in v2.x/v3.x.

// Context setup (once per class — NOT in each test)
private readonly IXrmFakedContext _context;

public AccountNumberPluginTests()
{
    _context = MiddlewareBuilder
        .New()
        .AddCrud()
        .SetLicense(FakeXrmEasyLicense.RPL_1_5)
        .Build();
}

[Fact]
public void When_Account_Created_Should_Set_Account_Number()
{
    // ARRANGE: build target and plugin context
    var target = new Entity("account") { Id = Guid.NewGuid(), ["name"] = "Contoso" };

    var pluginContext = new XrmFakedPluginExecutionContext
    {
        MessageName      = "Create",
        Stage            = 20, // PreOperation
        InputParameters  = new ParameterCollection { { "Target", target } },
        PreEntityImages  = new EntityImageCollection(),
        PostEntityImages = new EntityImageCollection()
    };

    // ACT
    _context.ExecutePluginWith<AccountNumberPlugin>(pluginContext);

    // ASSERT: PreOperation plugin mutates Target directly — assert on the same reference
    Assert.True(target.Contains("accountnumber"));
    Assert.StartsWith("ACC-", target["accountnumber"] as string);
}

Shorthand for simple plugins (no PreImage needed)

// messageName and stage are required parameters in v2.x/v3.x
_context.ExecutePluginWithTarget<AccountNumberPlugin>(target, "Create", 20);

Passing a PreImage

Use XrmFakedPluginExecutionContext directly — ExecutePluginWithTargetAndPreEntityImages is [Obsolete] in v2.6+:

var pluginContext = new XrmFakedPluginExecutionContext
{
    MessageName      = "Update",
    Stage            = 20,
    InputParameters  = new ParameterCollection { { "Target", target } },
    PreEntityImages  = new EntityImageCollection { { "PreImage", preImage } },
    PostEntityImages = new EntityImageCollection()
};
_context.ExecutePluginWith<ContactStatusPlugin>(pluginContext);

Workflow

0. Analyze the Plugin First

Before writing any test code, read the plugin source and extract these signals:

  • Registration: entity, message, stage (PreValidation=10 / PreOperation=20 / PostOperation=40)
  • Target type: Entity (Create/Update) or EntityReference (Delete)
  • Images: does it read PreEntityImages or PostEntityImages?
  • DI: does the constructor accept an interface? → create a mock inner class
  • Service calls: RetrieveMultiple / Create / Update / Delete → mock or seed context
  • Throws: every throw InvalidPluginExecutionException needs 3 tests (happy, throws, message)
  • Guards: every early return (entity guard, filtering attribute guard, depth guard) needs 1 test
  • Constructor guard: param ?? throw ArgumentNullException needs 1 null-argument test

See resources/plugin-analysis-test-generation.md for the complete decision tree and worked examples for Create, Update, and Delete plugins.

1. Setup Test Project

  • Create xUnit/NUnit/MSTest project targeting .NET Framework 4.6.2+ or .NET Core 3.1+
  • Install FakeXrmEasy.Plugins.v9 package (version 2.x for Framework, 3.x for Core)
  • Reference your plugin assembly
  • Optionally generate early-bound entities with pac modelbuilder build

2. Create Context in Constructor

FakeXrmEasyTestsBase does NOT exist in v2.x/v3.x. Build context via MiddlewareBuilder:

public class MyPluginTests
{
    private readonly IXrmFakedContext _context;
    private readonly IOrganizationService _service;

    public MyPluginTests()
    {
        _context = MiddlewareBuilder
            .New()
            .AddCrud()
            .SetLicense(FakeXrmEasyLicense.RPL_1_5)
            .Build();

        _service = _context.GetOrganizationService();

        // Optional: enable early-bound entities
        _context.EnableProxyTypes(Assembly.GetExecutingAssembly());
    }
}

3. Write Test Cases

For each plugin scenario:

  • Arrange: Create test data, configure XrmFakedPluginExecutionContext, set PreEntityImages
  • Act: Execute plugin with ExecutePluginWith<T>(pluginContext) (preferred) or ExecutePluginWithTarget<T> (simple cases)
  • Assert: Inspect Target reference (PreOperation) or query context (PostOperation)

4. Test Pipeline Simulation (Advanced)

For plugins that trigger other plugins or need full pipeline behavior:

// Setup middleware with pipeline simulation
_context = MiddlewareBuilder.New()
    .AddCrud()
    .AddPipelineSimulation()
    .UsePipelineSimulation()
    .UseCrud()
    .Build();

// Register plugin steps
_context.RegisterPluginStep<MyPlugin>(new PluginStepDefinition
{
    EntityLogicalName = "account",
    MessageName = "Create",
    Stage = ProcessingStepStage.Preoperation
});

// Execute normal service operation - plugin fires automatically
_service.Create(new Account { Name = "Test" });

Resource Files

Test Generation

  • resources/plugin-analysis-test-generation.md — Read a plugin and derive a complete test suite: analysis checklist, signal→pattern decision tree, required test categories, worked examples for Create/Update/Delete plugins

Core Testing Patterns

  • resources/setup-configuration.md — Install packages, project structure, test runners, early-bound setup
  • resources/testing-patterns.md — AAA pattern, ExecutePluginWith vs ExecutePluginWithTarget, assertions, test naming
  • resources/pipeline-simulation.md — RegisterPluginStep, entity images, stages, filtering attributes, execution order
  • resources/advanced-scenarios.md — Dependency injection, mocking, interaction testing, metadata

Advanced Features

  • resources/bulk-operations.md — CreateMultiple, UpdateMultiple, UpsertMultiple testing, IPluginExecutionContext4
  • resources/file-storage-testing.md — File/image column testing, upload/download, size validation, MIME types
  • resources/async-testing.md — IOrganizationServiceAsync, IOrganizationServiceAsync2, async/await patterns (v3.x only)
  • resources/telemetry-logging.md — ILogger integration, structured logging, performance metrics, Application Insights

Data & Queries

  • resources/testing-data-relationships.md — Entity references, 1:N/N:N relationships, associate/disassociate, hierarchies
  • resources/query-testing.md — FetchXML, QueryExpression, LINQ, aggregation, paging, joins

Specialized Scenarios

  • resources/codeactivities-testing.md — Workflow activity testing, InArguments, OutArguments, IWorkflowContext
  • resources/azure-functions-testing.md — Azure Functions with Dataverse, HTTP triggers, timer triggers, dependency injection
  • resources/custom-messages.md — Custom Actions, Custom APIs, generic message executors, entity-bound operations

Migration & Maintenance

  • resources/migration-guide.md — Migrating from FakeXrmEasy v1.x to v2.x/v3.x, breaking changes, best practices

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.