加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:52:06 所属栏目:百科 来源:网络整理
导读:我了解到OWIN有一个很棒的Microsoft.Owin.Testing库,可以让你在内存中测试你的web应用程序.但是,在访问编写测试代码复杂的资源之前,我的站点需要身份验证. 使用Microsoft.Owin.Testing时,是否有一种方便的“模拟”身份验证方法? 我希望我的单元测试不需要进
我了解到OWIN有一个很棒的Microsoft.Owin.Testing库,可以让你在内存中测试你的web应用程序.但是,在访问编写测试代码复杂的资源之前,我的站点需要身份验证.

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

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

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

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

[Test]
public async void AccessAuthenthicatedResourceTest()
{
    const string ClientId = "";
    const string RedirectUri = "";
    const string Authority = "";

    TestServer server = TestServer.Create(
        app =>
            {
                //Configure Open ID Connect With Cookie Authenthication
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
                app.USEOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                    {
                    ClientId = ClientId,RedirectUri = RedirectUri,Authority = Authority
                    });

                // Requires Authentication
                app.Use(
                    async ( context,next ) =>
                        {
                            var user = context.Authentication.User;
                            if ( user == null
                                 || user.Identity == null
                                 || !user.Identity.IsAuthenticated )
                            {
                                context.Authentication.Challenge();
                                return;
                            }

                            await next();
                        } );

                app.Run( async context => await context.Response.WriteAsync( "My Message" ) );
            } );


    //Do or Bypass authenthication

    HttpResponseMessage message = await server.CreateRequest( "/" ).GetAsync();

    Assert.AreEqual("My Message",await message.Content.ReadAsStringAsync());
}

解决方法

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

并将其注入您的基类:

protected BaseController(IUnitOfWork data,IUserProvider userProvider)
        {
            this.data = data;
            this.userProvider = userProvider;
        }

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

var userMockReposioty = new Mock<IRepository<ApplicationUser>>();
            var userMockUserProvider = new Mock<IUserProvider>();
            userMockUserProvider.Setup(x => x.GetUserName())
                .Returns("FakeUserName");

            userMockUserProvider.Setup(x => x.GetUserId())
              .Returns("c52b2a96-8258-4cb0-b844-a6e443acb04b");

 mockUnitOfWork.Setup(x => x.Users).Returns(userMockReposioty.Object);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读