Home > Software design >  How to mock GraphServiceClient with Header?
How to mock GraphServiceClient with Header?

Time:11-09

How to mock IGraphService with header?

List<Option> requestOptions = new List<Option>();

requestOptions.Add(new QueryOption("$count", "true"));

var test = await _graphServiceClient.Me.TransitiveMemberOf
                    .Request(requestOptions)
                    .Header("ConsistencyLevel", "eventual")
                    .Filter("startsWith(displayName,'a')")
                    .GetAsync();

What I tried so far.. but returning System.NotSupportedException

System.NotSupportedException : Unsupported expression: ... => ....Header(It.IsAny(), It.IsAny()) Extension methods (here: HeaderHelper.Header) may not be used in setup / verification expressions.

mockGraph.Setup(x => x.Me
                      .TransitiveMemberOf
                      .Request(It.IsAny<List<Option>>())
                      .Header(It.IsAny<string>(), It.IsAny<string>())
                      .Filter(It.IsAny<string>())
                      .ReturnsAsync(page);

CodePudding user response:

You can't mock extension methods like .Header(). Header() method creates a new instance of HeaderOption class and adds it to request headers.

Add ConsistencyLevel header to requestOptions collection by adding HeaderOption.

List<Option> requestOptions = new List<Option>();

requestOptions.Add(new QueryOption("$count", "true"));
// another way how to add header
requestOptions.Add(new HeaderOption("ConsistencyLevel", "eventual"));

// removed calling .Header method
var test = await _graphServiceClient.Me.TransitiveMemberOf
                .Request(requestOptions)
                .Filter("startsWith(displayName,'a')")
                .GetAsync();

Modify unit test

// removed calling .Header method
mockGraph.Setup(x => x.Me
                  .TransitiveMemberOf
                  .Request(It.IsAny<List<Option>>())
                  .Filter(It.IsAny<string>())
                  .ReturnsAsync(page);
  • Related