I post Unit testing Microsoft Graph SDK Client with moq library the other day, but I encounter a challenge when I need to write a bit more complex query.
Graph SDK with SELECT query
I use following code to get GraphUser object, which I specify several fields explicitly by using SELECT Linq.
Microsoft.Graph.User graphUser = await this.graphServiceClient.Users["<userId>"]
.Request()
.Select(u => new
{
u.Id,
u.BusinessPhones,
u.GivenName
})
.GetAsync();
Unit Test
This is the mock I use to cover above code. There maybe better way to do it but it's working anyway :)
Mock<IAuthenticationProvider> mockedIAuthenticationProvider = new ();
Mock<IHttpProvider> mockedIHttpProvider = new ();
Mock<GraphServiceClient> mockedGraphServiceClient = new (mockedIAuthenticationProvider.Object, mockedIHttpProvider.Object);
mockedGraphServiceClient.Setup(x => x.Users[It.IsAny<string>()]
.Request()
.Select(It.IsAny<Expression<Func<Microsoft.Graph.User, object>>>())
.GetAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(new Microsoft.Graph.User() { Id = Guid.NewGuid().ToString(), BusinessPhones = new List<string>(), GivenName = "Test" });
I use It.IsAny<Expression<Func<Microsoft.Graph.User, object>>>()
as an argument to Select method which covers any combination of properties.
Hope this article will help myself in the future as I shall forget this sooner or later.
Top comments (2)
@kenakamu do you have unit test code for NUnit framework? I have exactly same logic to get GraphUser object.
I can Substitute for (IGraphServiceUsersCollectionRequestBuilder). But I am not able to Returns(the Microsoft User object) to collection request builder object.
I haven't personally tried nunit but it should work quite similar way