Skip to content

Instantly share code, notes, and snippets.

@Adam--
Last active February 14, 2021 13:58
Show Gist options
  • Save Adam--/b503168e4f568658a172c25dc98b53a8 to your computer and use it in GitHub Desktop.
Save Adam--/b503168e4f568658a172c25dc98b53a8 to your computer and use it in GitHub Desktop.
Testing CloudTable dependent code using the Azure Storage Emulator and NUnit
public class TestingCloudTableWithAzureStorageEmulator
{
private CloudTableClient developmentCloudTableClient;
private CloudTable emulatedCloudTable;
[OneTimeSetUp]
public void OneTimeSetUp()
{
var azureStorageEmulatorProcess = Process.Start("C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\Storage Emulator\\AzureStorageEmulator.exe", "start");
azureStorageEmulatorProcess?.WaitForExit(2000);
this.developmentCloudTableClient = CloudStorageAccount.DevelopmentStorageAccount.CreateCloudTableClient();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
var azureStorageEmulatorProcess = Process.Start("C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\Storage Emulator\\AzureStorageEmulator.exe", "stop");
azureStorageEmulatorProcess?.WaitForExit(2000);
}
[SetUp]
public void SetUp()
{
this.emulatedCloudTable = this.developmentCloudTableClient.GetTableReference("unittests");
if (this.emulatedCloudTable.Exists())
{
this.emulatedCloudTable.Delete();
}
this.emulatedCloudTable.Create();
}
[TearDown]
public void TearDown()
{
this.emulatedCloudTable.Delete();
}
}
@viviandeveloper
Copy link

Very interesting discussion and something I've been thinking about how best to test an Azure function with a table binding. I had thought about an approach similar to what's in this gist relying on Azure Storage Emulator but I felt it's not isolated and repeatable enough. Fortunately CloudTableClient exposes a DelegatingHandler property which you can assign a stub handler to providing the JSON response that would come back from the storage account.

Here is an example of how it works https://gist.github.com/vivianroberts/4bf161fdd6a9692d202888130e84df6b

To get the structure of the responses I use Azure Cli with the AZURE_STORAGE_CONNECTION_STRING environment variable set to "UseDevelopmentStorage=true" and then set up a proxy in Postman on 10002 to capture the requests. Next I switch off the proxy and start Azure Storage Emulator and fire the captured requests from Postman to get the response body.

Hopefully this approach provides a good balance between all the suggestions in this discussion 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment