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 AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

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

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay