Using Moq to Mock KeyVaultClient for Unit Test C#

I am trying to mock the KeyVaultClient using mock so that my unit test won't depend on my Azure KeyVault service when I run the test. Is there any code similar to what I used to mock the 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);

1 answer

  • answered 2022-04-13 05:23 Deep

    As suggested by Hyden:

    Moq can only mock methods that are marked as virtual or interfaces. I suggest wrapping SecretClient in your own class, and create your own interface from it.

    You can try this example of Mock<SecretClient>():

    // Create a mock response
    var mockResponse = new Mock<Response>();
    
    // Create a mock value
    var mockValue = SecretModelFactory.KeyVaultSecret(
        SecretModelFactory.SecretProperties(new Uri("http://example.com"))
    );
    
    // Create a client mock
    var mock = new Mock<SecretClient>();
    
    // Setup client method
    mock.Setup(c => c.GetSecret("Name", null, default))
        .Returns(Response.FromValue(mockValue, mockResponse.Object));
    
    // Use the client mock
    SecretClient client = mock.Object;
    KeyVaultSecret secret = client.GetSecret("Name");
    

    You can refer to How to unit test with Moq the Azure Key Vault, Create Unit Test for a function in C# that uses SecretClient.GetSecret function and Unit testing and mocking with Azure SDK .NET

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum