【问题标题】:How to mock Microsoft Graph APIs GraphServiceClient using moq如何使用 moq 模拟 Microsoft Graph API GraphServiceClient
【发布时间】:2022-01-19 13:42:05
【问题描述】:

我的项目正在使用 GraphServiceClient 使用以下代码获取用户组名称。这也是使用 Microsoft.Identity.Web 包,因此 GraphServiceClient 是通过构造函数注入的。

 var group = await graphClient.Me.TransitiveMemberOf
                             .Request()
                             .GetAsync();

然后使用 group 变量获取组的 DisplayName。

我想使用 NUnit 和 Moq 对上述代码进行单元测试。

 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(???);

ReturnAsync 将返回 IUserTransitiveMemberOfCollectionWithReferencesPage,但是我怎样才能给它一个默认值,以便我可以测试实际获取 displayName 的方法的其余部分

提前致谢。

【问题讨论】:

  • 创建一个返回的任何东西的模拟并使用它
  • 显示更多被测主题和测试本身,以便提供正确答案

标签: microsoft-graph-api asp.net-core-webapi


【解决方案1】:

创建UserTransitiveMemberOfCollectionWithReferencesPage 的新实例,并将新的Group 项添加到当前页面。

UserTransitiveMemberOfCollectionWithReferencesPage page = new 
UserTransitiveMemberOfCollectionWithReferencesPage
{
    AdditionalData = new Dictionary<string, object>(),
};
page.Add(new Group { DisplayName = "MyName" });

ReturnsAsync方法中的返回页面

mockGraphClient.Setup(c => c.Me.TransitiveMemberOf.Request().GetAsync(CancellationToken.None))
    .ReturnsAsync(() => page);

【讨论】:

  • 非常感谢
猜你喜欢
  • 2018-06-20
  • 2012-03-18
  • 2010-10-19
  • 2016-09-30
  • 2019-10-06
  • 1970-01-01
  • 2020-10-27
  • 2012-06-01
  • 2018-12-27
相关资源
最近更新 更多