单元测试 Graph SDK PageIterator

Unit Testing Graph SDK PageIterator

我正在创建一项使用 Microsofts Graph SDK 的服务,该 SDK 具有从 Active Directory 检索所有应用程序的方法。最初,我只考虑了一个页面就编写了该方法,并成功模拟了单元测试中的调用,如下所示。

方法

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

    return applicationFirstPage;
}

单元测试

[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);
}

然后我继续从默认查询扩展该方法并遍历所有页面以获取所有应用程序的列表。我使用 PageIterator,如 docs 中所述。当我去更新单元测试时,我一直在努力调整它们以包括 PageIterator.

调用 await pageIterator.IterateAsync(); 会引发 null ref 异常,我想不出我该如何模拟或绕过它。

扩展方法

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;
}

对于如何用单元测试覆盖此方法的任何帮助或建议,我将不胜感激。提前致谢。

pageIterator.IterateAsync() 内部访问 page.AdditionalDataAdditionalData 未在 GraphServiceApplicationsCollectionPage.

的构造函数中初始化

您必须初始化 AdditionalData

GraphServiceApplicationsCollectionPage page = new GraphServiceApplicationsCollectionPage 
{
    AdditionalData = new Dictionary<string, object>()
};

PageIterator