博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NET Core 2.0 单元测试中初识 IOptionsMonitor<T>
阅读量:6942 次
发布时间:2019-06-27

本文共 1550 字,大约阅读时间需要 5 分钟。

在针对下面设置 CookieAuthenticationOptions 的扩展方法写单元测试时遇到了问题。 

public static IServiceCollection AddCnblogsAuthentication(this IServiceCollection services,     IConfigurationSection redisConfiguration,     Action
configureOption = null){ //...}

想通过下面的单元测试验证对 CookieAuthenticationOptions 的设置是否生效:

public void AddCnblogsAuthenticationTest(){    IServiceCollection services = new ServiceCollection();    var builder = new ConfigurationBuilder();    builder.AddInMemoryCollection(new Dictionary
{ ["redis"] = JsonConvert.SerializeObject(new CnblogsRedisOptions()) }); var configuration = builder.Build(); services.AddCnblogsAuthentication(configuration.GetSection("redis"), option => { option.LoginPath = "/users/signin"; }); var options = services.BuildServiceProvider() .GetRequiredService
>().Value; Assert.Equal("/users/signin", options?.LoginPath);}

但通过依赖注入解析 IOptions<CookieAuthenticationOptions> 接口得到的 CookieAuthenticationOptions 实例的值都是默认值, AddCnblogsAuthentication() 中的设置没生效。

后来查看  的实现代码才知道需要通过 IOptionsMonitor<CookieAuthenticationOptions> 接口解析,而且需要调用该接口的 Get() 方法(而不是 CurrentValue 属性)根据指定的 AuthenticationScheme 才能获取到所需的 CookieAuthenticationOptions 实例。

public void AddCnblogsAuthenticationTest(){    //...    var options = services.BuildServiceProvider()        .GetRequiredService
>() .Get(CookieAuthenticationDefaults.AuthenticationScheme); Assert.Equal("/users/signin", options?.LoginPath);}

转载地址:http://tjinl.baihongyu.com/

你可能感兴趣的文章
详解MySQL性能优化(二)
查看>>
详解KMP算法【转】
查看>>
计算机网络中通信协议都有哪些
查看>>
CentOS挂Windows的NFS备忘
查看>>
【死磕jeesite源码】mybatis动态调用表名和字段名
查看>>
【C002】Excel VBA - 文件打开关闭
查看>>
对WF工作流异常(Event on interface type for instance id cannot be delivered)的一点总结....
查看>>
目前常用的加密解密算法
查看>>
近期的一点感慨
查看>>
为什么Linux不需要碎片整理?
查看>>
EasyARM i.mx28学习笔记——开箱试用总结
查看>>
ASP怎么解除文件上传200kb限制
查看>>
Xshell选中的同时把内容复制到剪贴板(还可以设置设置文本分隔符)
查看>>
laravel的中间件demo
查看>>
Linux守护进程的编程实现
查看>>
ISCSI工作流程target和initiator
查看>>
Oracle密码过期the password has expired
查看>>
linux grep常用参数
查看>>
button 按钮,结合onclick事件,验证和提交表单
查看>>
<转>python字典排序 关于sort()、reversed()、sorted()
查看>>