【问题标题】:Using Moq to Mock KeyVaultClient for Unit Test C#使用 Moq 模拟 KeyVaultClient 进行单元测试 C#
【发布时间】:2022-10-13 02:52:58
【问题描述】:

我正在尝试使用 mock 模拟 KeyVaultClient,以便我的单元测试在运行测试时不会依赖于我的 Azure KeyVault 服务。有没有类似于我用来模拟 SecretClient 的代码?

// Create a page of enumeration results
Page<SecretProperties> secretResponsePage = Page<SecretProperties>.FromValues(
    new[] {
              new SecretProperties("secret1"),
              new SecretProperties("secret2"),
              new SecretProperties("secret3"),
            },
            continuationToken: null,
            Mock.Of<Response>());

// Create a pageable that consists of a single page
AsyncPageable<SecretProperties> pageable = AsyncPageable<SecretProperties>.FromPages(new[] { secretResponsePage });

// Setup a client mock object to return the pageable when GetPropertiesOfSecretsAsync is called
var clientMock = new Mock<SecretClient>();
     clientMock.Setup(c => c.GetPropertiesOfSecretsAsync(It.IsAny<CancellationToken>()))
            .Returns(pageable);

【问题讨论】:

  • Moq 只能模拟标记为 virtual 的方法或接口。我建议将SecretClient 包装在您自己的类中,并从中创建您自己的界面。

标签: c# azure unit-testing nunit


【解决方案1】:
    public static KeyVaultService _clientService;
    private static Mock<IConfiguration> _mockConfig;

    public KeyVaultServiceTest()
    {
        _mockConfig = new Mock<IConfiguration>();            
        _clientService = new KeyVaultService(configuration);
    }    


    [TestMethod]
    public async Task GetSecretKeyVault_UnitTest()
    {
        string secret = "This is sceret key";

        Mock<SecretBundle> mockSecret = new Mock<SecretBundle>();
        mockSecret.SetupGet(x => x.Value).Returns("secret");

        Mock<KeyVaultClient> clientMock = new Mock<KeyVaultClient>();
        clientMock.Setup(x => x.GetSecretAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(mockSecret.Object));

        _clientService.SetServiceClient(clientMock.Object);
        _clientService.GetSecretKeyVault("test");   
    }

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多