DEV Community

Manu Radhakrishnan
Manu Radhakrishnan

Posted on

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay