Unit testing cosmos persistence in an handler

Hi,

i have the following in a handler where i get hold of the session to retrieve and update the customer object, is there a way we can unit test (mock) these 2 lines of code ?, i might have missing something but the documentation did not contain any samples on how unit test these, any links or guidance would be really helpfull.


     var session = context.SynchronizedStorageSession.CosmosPersistenceSession();
     var queryable = session.Container.GetItemLinqQueryable<Customer>(true);

var cust= session.Container.GetItemLinqQueryable<Customer>(true).Where(x => x.CustomerTenantId == CustomerId).FirstOrDefault();

I assume that of those two lines, you want to mock out the code that queries CosmosDB?

If that’s true, then the easiest way is to put those lines of code behind an interface that you can replace at test time. E.g.

interface IProvideCustomer
{
    Customer GetCustomer(IMessageHandlerContext context);
}


class CosmosCustomerProvider : IProvideCustomer
{
    Customer GetCustomer(IMessageHandlerContext context)
    {
        var session = context.SynchronizedStorageSession.CosmosPersistenceSession();
         var queryable = session.Container.GetItemLinqQueryable<Customer>(true);
    }
}

Which then means in your test you can fake it out with a fake implementation:

[Test]
public Task TestCustomer()
{
   var fakeCustomerProvider = new FakeCustomerProvider();

    var handler = new HandlerIWantToTest(fakeCustomerProvider);
    await handler.Handle(new MyMessage(), context );

    Assert.True(FakeCustomerProvider.WasCalled);
}

class FakeCustomerProvider : IProvideCustomer
{
    static bool WasCalled = false;
    Customer GetCustomer(IMessageHandlerContext context)
    {
        FakeCustomerProvider.WasCalled = true;
        return new Customer { };
    }
}

Hi @Nen_Zax

The package contains a class called TestableCosmosSynchronizedStorageSession. You can use that to fake the synchronized storage session. Here is a test that demonstrates it.

From there you can use your preferred way of faking or mocking the container access. Container provides most of the methods as virtual members. You can override them manually or use a faking/mocking library of your choice.

We usually prefer hand rolled fakes. For example see

Hope that helps
Daniel

1 Like