在测试项目中使用 IDataProtectionProvider? [英] Using IDataProtectionProvider in test project?

查看:49
本文介绍了在测试项目中使用 IDataProtectionProvider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Web API 中使用 IDataProtectionProvider 时,IoC 容器配置为 AddDataProtection (services.AddDataProtection();) 并启用使用 DI 来检索服务中的 IDataProtectionProvider:

When using IDataProtectionProvider in a Web API, the IoC container is configured with AddDataProtection (services.AddDataProtection();) and enables the use of DI to retrieve a IDataProtectionProviderin a service as such:

private readonly IDataProtectionProvider _dataProtectionProvider;

public CipherService(IDataProtectionProvider dataProtectionProvider)
{
    _dataProtectionProvider = dataProtectionProvider;
}

如果我想测试我的 CipherService(在我的例子中使用 Xunit),我将无法在不使用 DI 的情况下完成这项工作,所以我的问题是;

If I would like to test my CipherService (in my case using Xunit), I will not be able to make this work without using DI, so my question is;

问:如何在测试项目中使用 DI 或以其他方式制作 IDataProtectionProvider?

推荐答案

这里是我如何使用 Moq 框架做到的:

Here how I did it using Moq framework:

Mock<IDataProtector> mockDataProtector = new Mock<IDataProtector>();
mockDataProtector.Setup(sut => sut.Protect(It.IsAny<byte[]>())).Returns(Encoding.UTF8.GetBytes("protectedText"));
mockDataProtector.Setup(sut => sut.Unprotect(It.IsAny<byte[]>())).Returns(Encoding.UTF8.GetBytes("originalText"));

Mock<IDataProtectionProvider> mockDataProtectionProvider = new Mock<IDataProtectionProvider>();
mockDataProtectionProvider.Setup(s => s.CreateProtector(It.IsAny<string>())).Returns(mockDataProtector.Object);

在需要传入 IDataProtectionProvider 的地方,我使用:

And where I need to pass in the IDataProtectionProvider, I use:

mockDataProtectionProvider.Object

对于需要真正的 DataProtectionProvider 的集成测试场景,您可以使用以下 MSDN 文档 文章.

For an integration test scenario, where you want a real DataProtectionProvider, you can use the following MSDN Documentation article.

希望这会有所帮助.

这篇关于在测试项目中使用 IDataProtectionProvider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆