c# – 如何对使用OWIN Cookie Authenthication的代码进行单元测试

前端之家收集整理的这篇文章主要介绍了c# – 如何对使用OWIN Cookie Authenthication的代码进行单元测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我了解到OWIN有一个很棒的Microsoft.Owin.Testing库,可以让你在内存中测试你的web应用程序.但是,在访问编写测试代码复杂的资源之前,我的站点需要身份验证.

使用Microsoft.Owin.Testing时,是否有一种方便的“模拟”身份验证方法

我希望我的单元测试不需要进入进程外STS,我宁愿不需要编写以编程方式登录内存中STS的代码(例如Thinktecture.IdentityServer.v3).

我想出的最简单的解决方案是禁用单元测试的认证代码,其中我不是粉丝.

我正在使用OpenID Connect和Cookie身份验证.这是一个包含的例子.需要为实际服务器填写OpenId Connect的配置字符串.

  1. [Test]
  2. public async void AccessAuthenthicatedResourceTest()
  3. {
  4. const string ClientId = "";
  5. const string RedirectUri = "";
  6. const string Authority = "";
  7.  
  8. TestServer server = TestServer.Create(
  9. app =>
  10. {
  11. //Configure Open ID Connect With Cookie Authenthication
  12. app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
  13. app.UseCookieAuthentication(new CookieAuthenticationOptions());
  14. app.USEOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
  15. {
  16. ClientId = ClientId,RedirectUri = RedirectUri,Authority = Authority
  17. });
  18.  
  19. // Requires Authentication
  20. app.Use(
  21. async ( context,next ) =>
  22. {
  23. var user = context.Authentication.User;
  24. if ( user == null
  25. || user.Identity == null
  26. || !user.Identity.IsAuthenticated )
  27. {
  28. context.Authentication.Challenge();
  29. return;
  30. }
  31.  
  32. await next();
  33. } );
  34.  
  35. app.Run( async context => await context.Response.WriteAsync( "My Message" ) );
  36. } );
  37.  
  38.  
  39. //Do or Bypass authenthication
  40.  
  41. HttpResponseMessage message = await server.CreateRequest( "/" ).GetAsync();
  42.  
  43. Assert.AreEqual("My Message",await message.Content.ReadAsStringAsync());
  44. }

解决方法

我认为模拟是测试控制器中的一部分代码.
您可以使用mock为用户注入虚假数据.您必须为用户提供程序创建一个接口.
  1. public interface IUserProvider
  2. {
  3. string GetUserId();
  4. string GetUserName();
  5. }

并将其注入您的基类:

  1. protected BaseController(IUnitOfWork data,IUserProvider userProvider)
  2. {
  3. this.data = data;
  4. this.userProvider = userProvider;
  5. }

之后,您可以像这样模拟IUserProvider:

  1. var userMockReposioty = new Mock<IRepository<ApplicationUser>>();
  2. var userMockUserProvider = new Mock<IUserProvider>();
  3. userMockUserProvider.Setup(x => x.GetUserName())
  4. .Returns("FakeUserName");
  5.  
  6. userMockUserProvider.Setup(x => x.GetUserId())
  7. .Returns("c52b2a96-8258-4cb0-b844-a6e443acb04b");
  8.  
  9. mockUnitOfWork.Setup(x => x.Users).Returns(userMockReposioty.Object);

我希望这会对你有所帮助.

猜你在找的C#相关文章