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

vos*_*d01 7 .net c# unit-testing owin katana

我了解到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());
}
Run Code Online (Sandbox Code Playgroud)

小智 1

我认为模拟是测试控制器中的部分代码。您可以使用模拟为用户注入虚假数据。您必须为用户提供者创建一个接口。

 public interface IUserProvider
    {
        string GetUserId();
        string GetUserName();
    }
Run Code Online (Sandbox Code Playgroud)

并将其注入到您的基类中:

 protected BaseController(IUnitOfWork data, IUserProvider userProvider)
        {
            this.data = data;
            this.userProvider = userProvider;
        }
Run Code Online (Sandbox Code Playgroud)

之后你可以像这样模拟 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);
Run Code Online (Sandbox Code Playgroud)

我希望这会对您有所帮助。