How to mock Microsoft Graph APIs GraphServiceClient using moq

Newbie Dev 156 Reputation points
2021-12-14T20:12:54.143+00:00

Hi,

My project is using GraphServiceClient to get the user Group Names using the below code.

var group = await graphClient.Me.TransitiveMemberOf
                            .Request()
                            .GetAsync();

The group variable is then used to get the DisplayName of the group.

I want to unit test the above code using Moq.

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

mockGraphClient.Setup(c => c.Me.TransitiveMemberOf.Request().GetAsync(CancellationToken.None)).ReturnsAsync(???);

The ReturnAsync will return IUserTransitiveMemberOfCollectionWithReferencesPage, but how can I give a default value for it so I can test the rest of the method which actually gets the displayName

Thanks in advance.

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
43,567 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Thuy Nguyen 5 Reputation points Microsoft Employee
    2025-05-06T06:11:35.72+00:00

    The new Mock<IHttpProvider>() mock gives me an error:

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.