Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading