Is there any option for Mock EncryptAsync() in Azure.Security.KeyVault.Keys.Cryptography

manu_vr

Manu Radhakrishnan

Posted on June 11, 2024

Is there any option for Mock EncryptAsync() in Azure.Security.KeyVault.Keys.Cryptography

I am trying to mock the functionality of the EncryptAsync method in Azure.Security.KeyVault.Keys.Cryptography.CryptographyClient.

This is the method I am trying to cover in my unit test.

public KeyVaultClientWrapper(KeyClient keyClient, SecretClient secretClient, CryptographyClient cryptographyClient)
    {
        _keyClient = keyClient;
        _cryptographyClient = cryptographyClient;
        _secretClient = secretClient;
    }

    public async Task<EncryptResult> EncryptAsync(string keyName, string algorithm, byte[] plainText, CancellationToken cancellationToken = default)
    {
        return await _cryptographyClient.EncryptAsync(algorithm, plainText, cancellationToken);
    }
Enter fullscreen mode Exit fullscreen mode

I'm unable to create new object of EncryptResult that needs to returned from the mock EncryptAsync method because there is no Set for EncryptResult

var _mockKeyVaultClient = new Mock<IKeyVaultClient>();
    var _mockCryptoClient = new Mock<CryptographyClient>();
    mockCryptoClient
            .Setup(client => client.EncryptAsync(EncryptionAlgorithm.AES, plaintext, default))
            .ReturnsAsync(new EncryptResult { Ciphertext = ciphertext });
Enter fullscreen mode Exit fullscreen mode

How can I change this mock class so that EncryptAsync returns a valid EncryptResult object while running the test method?

Is there any alternate option for testing the same?

.NETCore

💖 💪 🙅 🚩
manu_vr
Manu Radhakrishnan

Posted on June 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related