DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

6 2

C#: Unit Testing Azure Files SDK

Azure Files is great service to store files like local disk. I use C# SDK to access to the service, but unit testing was not straight forward.

Sample code

Let's imagine we have C# code as below, which returns all share names from the Azure Files. I use DI for ShareServiceClient here. The code is quite simple, eh?

using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;

namespace AzureFilesSample;

public class AzureFileSampleService
{
    private readonly ShareServiceClient shareServiceClient;

    public AzureFileSampleService(ShareServiceClient shareServiceClient)
    {
        this.shareServiceClient = shareServiceClient;
    }
    public async Task<List<string>> GetFileSharesAsync()
    {
        List<string> fileShares = new List<string>();
        await foreach (ShareItem item in shareServiceClient
            .GetSharesAsync()
            .WithCancellation(CancellationToken.None))
        {
            fileShares.Add(item.Name);
        }

        return fileShares;
    }
}
Enter fullscreen mode Exit fullscreen mode

Unit test

To write unit test for the above code, we need to mock ShareServiceClient. However, I cannot instantiate ShareItem as it only has internal constructor. After I browse its source code in github, I found ShareModelFactory class which let us instantiate related models.

This is the unit testing code. I use xUnit and moq library.

  • Use ShareModelFactory to instantiate items
  • Refer to Azure Mocking page to mock Azure response related object.
[Fact]
public async Task Test1()
{
    Mock<ShareServiceClient> mockedShareServiceClient = new Mock<ShareServiceClient>();
    ShareItem shareItem1 = ShareModelFactory.ShareItem("name1", ShareModelFactory.ShareProperties());
    ShareItem shareItem2 = ShareModelFactory.ShareItem("name2", ShareModelFactory.ShareProperties());
    ShareItem[] pageValues = new[] { shareItem1, shareItem2 };
    Page<ShareItem> page = Page<ShareItem>.FromValues(pageValues, default, new Mock<Response>().Object);
    Pageable<ShareItem> pageable = Pageable<ShareItem>.FromPages(new[] { page });
    AsyncPageable<ShareItem> asyncPageable = AsyncPageable<ShareItem>.FromPages(new[] { page });
    mockedShareServiceClient.Setup(x => x.GetSharesAsync(ShareTraits.None, ShareStates.None, null, CancellationToken.None))
        .Returns(asyncPageable);

    AzureFileSampleService service = new AzureFileSampleService(mockedShareServiceClient.Object);

    var results = await service.GetFileSharesAsync();

    Assert.Equal("name1", results.First());
    Assert.Equal("name2", results.Last());
}
Enter fullscreen mode Exit fullscreen mode

Summary

Obviously, Azure Mocking is a great resource for unit test but we need to see source code to figure out how to write unit test time to time.

Reference

Async Enumerables

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay