Mocking CloudStorageAccount and CloudTable for Azure table storage

To add to the answer here, as you're aiming to use a mocking framework, simply setting up an object that inherits from CloudTable and provides a default constructor should allow you to Mock the inherited object itself and control what it returns:

public class CloudTableMock : CloudTable
{
    public CloudTableMock() : base(new Uri("http://127.0.0.1:10002/devstoreaccount1/screenSettings"))
    {
    }
}

Then it's just a case of creating the mock. I'm using NSubstitute so I did:

_mockTable = Substitute.For<CloudTableMock>();

but my guess is that Moq would allow:

_mockTableRef = new Mock<CloudTable>();
_mockTableRef.Setup(x => x.DoSomething()).ReturnsAsync("My desired result");
_mockTable = _mockTableRef.Object;

(My Moq is a bit rusty, so I'm guessing the syntax above isn't quite correct)


I was also struggling with implementing unit test for an Azure Function with a binding to Azure Table Storage. I got it finally working using a derived CloudTable class where I can override the methods I use and return fixed results.

/// <summary>
/// Mock class for CloudTable object
/// </summary>
public class MockCloudTable : CloudTable
{

    public MockCloudTable(Uri tableAddress) : base(tableAddress)
    { }

    public MockCloudTable(StorageUri tableAddress, StorageCredentials credentials) : base(tableAddress, credentials)
    { }

    public MockCloudTable(Uri tableAbsoluteUri, StorageCredentials credentials) : base(tableAbsoluteUri, credentials)
    { }

    public async override Task<TableResult> ExecuteAsync(TableOperation operation)
    {
        return await Task.FromResult(new TableResult
        {
            Result = new ScreenSettingEntity() { Settings = "" },
            HttpStatusCode = 200
        });
    }
}

I instantiated the mock class by passing an configuration string used for local storage by the storage emulator (see https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string).

var mockTable = new MockCloudTable(new Uri("http://127.0.0.1:10002/devstoreaccount1/screenSettings"));

In this example 'screenSettings' is the name of the table.

The mock class can now be passed to the Azure Function from your unit test.

Maybe this is what you are looking for?