Unit testing Microsoft Graph SDK Client with moq library

kenakamu

Kenichiro Nakamura

Posted on October 31, 2021

Unit testing Microsoft Graph SDK Client with moq library

According to this article, Microsoft Graph SDK 4.0, GraphServiceClient doesn't inherit IGraphServiceClient interface anymore. But this doesn't unit test more difficult as all methods are marked as virtual.

So we can simply mock all dependencies and use Setup method to mock any method for test purpose. One example we can find in the article is below.

// Arrange
var mockAuthProvider = new Mock<IAuthenticationProvider>();
var mockHttpProvider = new Mock<IHttpProvider>();
var mockGraphClient = new Mock<GraphServiceClient>(mockAuthProvider.Object, mockHttpProvider.Object);

ManagedDevice md = new ManagedDevice
{
    Id = "1",
    DeviceCategory = new DeviceCategory()
    {
        Description = "Sample Description"
    }
};

// setup the calls
mockGraphClient.Setup(g => g.DeviceManagement.ManagedDevices["1"].Request().GetAsync(CancellationToken.None)).Returns(Task.Run(() => md)).Verifiable();

// Act
var graphClient = mockGraphClient.Object;
var device = await graphClient.DeviceManagement.ManagedDevices["1"].Request().GetAsync(CancellationToken.None);

// Assert
Assert.Equal("1",device.Id);
Enter fullscreen mode Exit fullscreen mode

Summary

It's even easier to mock any method with latest version of SDK.

💖 💪 🙅 🚩
kenakamu
Kenichiro Nakamura

Posted on October 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related