Newbie
Newbie

Reputation: 873

How to mock Microsoft Graph APIs GraphServiceClient using moq

My project is using GraphServiceClient to get the user Group Names using the below code.This is also using Microsoft.Identity.Web package so GraphServiceClient is injected through constructor.

 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 NUnit and 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.

Upvotes: 1

Views: 2652

Answers (1)

user2250152
user2250152

Reputation: 20725

Create a new instance of UserTransitiveMemberOfCollectionWithReferencesPage and add a new Group item to the current page.

UserTransitiveMemberOfCollectionWithReferencesPage page = new 
UserTransitiveMemberOfCollectionWithReferencesPage
{
    AdditionalData = new Dictionary<string, object>(),
};
page.Add(new Group { DisplayName = "MyName" });

Return page in ReturnsAsync method

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

Upvotes: 4

Related Questions