How to Unit Testing Azure Storage in C# – Part 2/3

Unit testing Azure Storage

In first part and previous article we covered how to install Azurite, an Azure Storage Emulator. We have also learned how to fire-up a local emulator for testing.

Now we will build a small storage app that can do basic stuff like, read, write and delete, and then we will testing it with Azurite.

First of all I create a empty solution in Visual Studio 2022 and call it AzureBlobStorageApp. Than I will create my first library project and call it AzureBlobStorageApp .

I add Azure.Storage.Blobs NuGet package to my project.

<ItemGroup>
  <PackageReference Include="Azure.Storage.Blobs" Version="12.10.0" />
</ItemGroup>

Now lets create a class AzureBlobStorage.cs with a constructor that takes connection string and container name.

public AzureBlobStorage(string connectionString, string container)
{
    _blobContainerClient = new BlobContainerClient(connectionString, container);
    _blobContainerClient.CreateIfNotExists();
}

We will create 3 methods that Read, Create and Delete text file.

public async Task<string> ReadTextFile(string filename)
{
    var blob = _blobContainerClient.GetBlobClient(filename);
    if (!await _blobContainerClient.ExistsAsync()) return string.Empty;
    var reading = await blob.DownloadStreamingAsync();
    StreamReader reader = new StreamReader(reading.Value.Content);
    return await reader.ReadToEndAsync();
}

public async Task CreateTextFile(string filename, byte[] data)
{
    var blob = _blobContainerClient.GetBlobClient(filename);
    await using var ms = new MemoryStream(data, false);
    await blob.UploadAsync(ms, CancellationToken.None);
}

public async Task DeleteTextFile(string filename)
{
    var blobClient = _blobContainerClient.GetBlobClient(filename);
    await blobClient.DeleteAsync();
}

Now we create a new xunit test project and call it AzureBlobStorageApp.UnitTests

Check and eventually adding following dependencies, and of course add reference to our AzureBlobStorageApp project as well.

<ItemGroup>
  <PackageReference Include="Azure.Storage.Blobs" Version="12.10.0" />
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
  <PackageReference Include="xunit" Version="2.4.1" />
  <PackageReference Include="xunit.console" Version="2.4.1" />
  <PackageReference Include="xunit.runner.console" Version="2.4.1">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  </PackageReference>
  <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>

<ItemGroup>
  <ProjectReference Include="..\AzureBlobStorageApp\AzureBlobStorageApp.csproj" />
</ItemGroup>

Lets create a class AzureBlobStorageUnitTests with variable declaration and constructor:

private const string Content = "Some Data inside file Content";

private const string DefaultEndpointsProtocol = "http";
private const string AccountName = "devstoreaccount1";
private const string AccountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
private const string BlobEndpoint = "http://127.0.0.1:10000/devstoreaccount1";
private const string ConnectionString = $"DefaultEndpointsProtocol={DefaultEndpointsProtocol};AccountName={AccountName};AccountKey={AccountKey};BlobEndpoint={BlobEndpoint};";

private const string Container = "container-1";
public AzureBlobStorageUnitTests()
{
    _azureBlobStorage = new AzureBlobStorage(ConnectionString, Container);
}

Now what we want to achieve is to test if we can create blob file to our local storage, reading it and deleting it.

[Fact]
public async Task AzureBlobStorageTest()
{
    // Arrange
    await _azureBlobStorage?.CreateTextFile("file.txt", Encoding.UTF8.GetBytes(Content))!;

    // Act
    var readTextFile = await _azureBlobStorage.ReadTextFile("file.txt");
    
    // Assert
    Assert.Equal(Content, readTextFile);

    // Finalizing
    await _azureBlobStorage.DeleteTextFile("file.txt");
}

Now lets fire up our test, remember your azurite docker should be up and running.

Congrats, now you have just learned how to unit test your methods that for Azure Blob Storage on local environment with out need to having access to Azure Portal.

Download the project from GitHub.

Conclusion

In this article, we learned to interact our C# code with Azure Blob Storage on local environment. We created a Unit Test to test our Azure Blob Storage methods.

Now some of you would wonder and ask, this unit test works locally when my azurite docker is running, now how can I run this unit test on my GitHub action or Azure DevOps as part of CI (Continuous Integration) testing and still be able to fire up a docker image of Azurite?

This is what I will cover for GitHub action in next and last article.

Graphic credit
The banner in this article is design by my ❤️ 15 years son Jassin Fahmi 😀.

Leave a Reply

Your email address will not be published. Required fields are marked *