.NET Core 2.0 单元测试中初识 IOptionsMonitor<T>

发表于:2017-8-25 16:23

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:dudu    来源:51Testing软件测试网采编

  在针对下面设置 CookieAuthenticationOptions 的扩展方法写单元测试时遇到了问题。 
  public static IServiceCollection AddCnblogsAuthentication(this IServiceCollection services, 
      IConfigurationSection redisConfiguration, 
      Action<CookieAuthenticationOptions> configureOption = null)
  {
      //...
  }
  想通过下面的单元测试验证对 CookieAuthenticationOptions 的设置是否生效:
  public void AddCnblogsAuthenticationTest()
  {
      IServiceCollection services = new ServiceCollection();
      var builder = new ConfigurationBuilder();
      builder.AddInMemoryCollection(new Dictionary<string, string>
      {
          ["redis"] = JsonConvert.SerializeObject(new CnblogsRedisOptions())
      });
      var configuration = builder.Build();
      services.AddCnblogsAuthentication(configuration.GetSection("redis"),
          option =>
          {
              option.LoginPath = "/users/signin";
          });
      var options = services.BuildServiceProvider()
          .GetRequiredService<IOptions<CookieAuthenticationOptions>>().Value;
      Assert.Equal("/users/signin", options?.LoginPath);
  }
  但通过依赖注入解析 IOptions<CookieAuthenticationOptions> 接口得到的 CookieAuthenticationOptions 实例的值都是默认值, AddCnblogsAuthentication() 中的设置没生效。
  后来查看 CookieAuthenticationHandler 的实现代码才知道需要通过 IOptionsMonitor<CookieAuthenticationOptions> 接口解析,而且需要调用该接口的 Get() 方法(而不是 CurrentValue 属性)根据指定的 AuthenticationScheme 才能获取到所需的 CookieAuthenticationOptions 实例。
  public void AddCnblogsAuthenticationTest()
  {
      //...
      var options = services.BuildServiceProvider()
          .GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>()
          .Get(CookieAuthenticationDefaults.AuthenticationScheme);
      Assert.Equal("/users/signin", options?.LoginPath);
  }
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号