如何模拟Azure KeyVaultKey C#
我目前正在尝试单元测试一些Azure功能,并且该服务需要从Azure密钥库中获取keyVaultKey,该键将用于加密某些数据。我想设置以下操作的模拟,然后返回自己的自定义keyVaultKey。不幸的是,我不知道如何创建功能性keyVaultKey的实例。
KeyVaultKey key = await KeyClient.GetKeyAsync(KeyVaultEncryptionKey).ConfigureAwait(false);
我的模拟:
var keyClient = new Mock<KeyClient>();
var azureResponse = new Mock<Response>();
Response<KeyVaultKey> response = Response.FromValue(GetKey(), azureResponse.Object);
keyClient.Setup(c => c.GetKeyAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
private KeyVaultKey GetKey()
{
var generatedKey = RSA.Create();
var keyProperties = new KeyProperties("key");
var webKey = new Azure.Security.KeyVault.Keys.JsonWebKey(generatedKey, includePrivateParameters: true);
var keyVault = KeyModelFactory.KeyVaultKey(keyProperties, webKey);
return keyVault;
}
有人可以告诉我我的错误在哪里,并向我展示如何正确嘲笑KeyVaultKey?
I'm currently trying to unit test some Azure Functions and the service requires to get a KeyVaultKey from Azure Key Vault, key that will be used to encrypt some data. I would like to setup a mock of the operation below and return an own custom KeyVaultKey. Unfortunately, I'm unaware of how to create an instance of a functional KeyVaultKey.
KeyVaultKey key = await KeyClient.GetKeyAsync(KeyVaultEncryptionKey).ConfigureAwait(false);
My mock:
var keyClient = new Mock<KeyClient>();
var azureResponse = new Mock<Response>();
Response<KeyVaultKey> response = Response.FromValue(GetKey(), azureResponse.Object);
keyClient.Setup(c => c.GetKeyAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
private KeyVaultKey GetKey()
{
var generatedKey = RSA.Create();
var keyProperties = new KeyProperties("key");
var webKey = new Azure.Security.KeyVault.Keys.JsonWebKey(generatedKey, includePrivateParameters: true);
var keyVault = KeyModelFactory.KeyVaultKey(keyProperties, webKey);
return keyVault;
}
Could anyone show me where is my mistake and show me how to properly mock a KeyVaultKey?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这也取决于您也需要运行的测试类型,但是如果它是旋转Docker容器以提供钥匙库的测试双重选择的选择钥匙。
如果此选项对您的项目有意义,则可以尝试一下LowKey Vault: https:// github。 com/nagyesta/lowkey-vault
它也带有.NET POC: https://github.com/nagyesta/lowkey-vault-example-dotnet
It depends on the kind of test you need to run too, but in case it is an option to spin up a Docker container to provide a test double for Key Vault you could simply get a real key from the container instead of focusing on mocking the key.
If this option could make sense for your project, you could give Lowkey Vault a try: https://github.com/nagyesta/lowkey-vault
It comes with a .Net POC too: https://github.com/nagyesta/lowkey-vault-example-dotnet