Async

With the latest version of the Dataverse Service Client package (0.5.10 as of the date of this post) there is support for async methods.

These are available in 3.x versions of FakeXrmEasy that use that package.

There are 2 interfaces that support async methods:

  • IOrganizationServiceAsync: without cancellation tokens.
  • IOrganizationServiceAsync2: with cancellation tokens.

Middleware

You can get access to any of these interfaces by calling GetAsyncOrganizationService() or GetAsyncOrganizationService2() methods on a IXrmFakedContext after it has been fully built by middleware.

Example below:

If you want to use the async service with cancellation tokens:

public class FakeXrmEasyTestsBase
{
    protected readonly IXrmFakedContext _context;
    protected readonly IOrganizationServiceAsync2 _service;

    public FakeXrmEasyTestsBase() 
    {
        _context = MiddlewareBuilder
                        .New()
                        .AddCrud()
                        
                        .UseCrud()
                        .Build();

        _service = _context.GetAsyncOrganizationService2();
    }
}

How to retrieve the service that doesn’t use cancellation tokens:

public class FakeXrmEasyTestsBase
{
    protected readonly IXrmFakedContext _context;
    protected readonly IOrganizationServiceAsync _service;

    public FakeXrmEasyTestsBase() 
    {
        _context = MiddlewareBuilder
                        .New()
                        .AddCrud()
                        
                        .UseCrud()
                        .Build();

        _service = _context.GetAsyncOrganizationService();
    }
}

Async methods with xUnit

Testing async methods with xUnit is pretty much straightforward. You would just add the async keyword on every unit test so that any async method in the unit test could be “awaited”:

Here’s an example from the Azure functions test project on GitHub.

public class CreateContactTests : FakeXrmEasyTestsBase
{
    [Fact]
    public async void Should_create_contact()
    {
        var result = await CreateContactFn.CreateContact(_service, "Joe", "joe@satriani.com");
        Assert.True(result.Succeeded);
        
        var contacts = _context.CreateQuery("contact").ToList(); 
        Assert.Single(contacts);

        Assert.Equal("Joe", contacts[0]["firstname"]);
        Assert.Equal("joe@satriani.com", contacts[0]["emailaddress1"]);
    }
}