Unit Testing GraphApi PageIterator

I am creating a service that uses Microsofts Graph SDK which has a method for retrieving all applications from Active Directory. Originally I wrote the method with only a single page in mind and successfully mocked out the call in unit tests like below.

Method

public async Task<IList<Application>> GetAllApplicationsAsync1()
{
    var applicationFirstPage = await _graphServiceClient.Applications
            .Request()
            .GetAsync();

    return applicationFirstPage;
}

Unit Test

[Test]
public async Task GetAllApplicationsAsync_NoApplications_ReturnsEmptyAsync()
{
    // Arrange
    var graphServiceClientMock = new Mock<IGraphServiceClient>();

    // Create an empty page of applications
    GraphServiceApplicationsCollectionPage page = new GraphServiceApplicationsCollectionPage { };

    graphServiceClientMock.Setup(m => m.Applications.Request().GetAsync()).ReturnsAsync(() => page);
    var graphClient = new GraphClient(graphServiceClientMock.Object);

    // Act
    var apps = await graphClient.GetAllApplicationsAsync();

    // Assert
    Assert.That(apps, Is.Empty);
}

I then proceeded to extend the method from the default query and loop through all pages to get a list of all applications. I used PageIterator as outlined in the docs. When I went to update the unit tests I've struggled to adapt them to include PageIterator.

Calling await pageIterator.IterateAsync(); throws a null ref exception, and I cannot think of how I'd mock or get around that.

Extended Method

public async Task<IList<Application>> GetAllApplicationsAsync()
{
    var applicationFirstPage = await _graphServiceClient.Applications
            .Request()
            .GetAsync();

    List<Application> applications = new List<Application>();
    var pageIterator = PageIterator<Application>
        .CreatePageIterator(_graphServiceClient, applicationFirstPage, (a) =>
        {
            applications.Add(a);
            return true;
        });

    await pageIterator.IterateAsync();

    return applications;
}

I'd appreciate any help or advice on how to cover this method with unit tests. Thanks in advance.



Read more here: https://stackoverflow.com/questions/66268527/unit-testing-graphapi-pageiterator

Content Attribution

This content was originally published by SJC at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: