Owin.TestServer测试需要身份验证的中间件

时间:2016-03-14 19:25:06

标签: unit-testing owin owin-middleware

我有一个中间件方法需要 context.Authentication.User.Identity.Name 才能正确执行。但是,在编写单元测试时,这些属性显然为空,因为没有发生登录。我没有在这个中间件中使用Oauth或任何相关的身份验证(超出明显的名称属性),因为它应该在另一个中间件的其他地方处理(以促进我正在开发的组件的重用/灵活性)。有没有办法模拟/伪造这个值,所以我可以运行我的测试?我已经尝试了一切我能想到的伪造登记的东西,我只是坚持到这一步。要明确的是,中间件需要的值不是webapi调用等。

//Arrange
var resolver = A.Fake<IDependencyResolver>();
A.CallTo(() => resolver.GetService(typeof(ISomeService))).Returns(new TestService());

using (var server = TestServer.Create(app =>
{
    app.UseMyMiddleware(new MyMiddlewareOptions()
    {
        DependencyResolver = resolver
    });

    app.Run(async ctx =>
    {
        await ctx.Response.WriteAsync(ctx.Request.Path.Value);
    });
}))
{
    //Act
    var response = await server.CreateRequest("/").GetAsync();

    //Assert
    A.CallTo(() => resolver.GetService(typeof(ISomeService)))
                           .MustHaveHappened(Repeated.Exactly.Once);
    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
    //Etc.
}

2 个答案:

答案 0 :(得分:0)

所以这是一种我认为不会激动的方式,但它能完成这项工作。我会等待接受,因为我认为应该有更好的方法。

public class TestFakeLoginMiddleware : OwinMiddleware
{
    public TestFakeLoginMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        var identity = A.Fake<IIdentity>();
        A.CallTo(() => identity.Name).Returns("TEST@domain.local");
        var user = new ClaimsPrincipal(identity);
        context.Request.Context.Authentication.User = user;
        await Next.Invoke(context);
    }
}

答案 1 :(得分:0)

有点晚了,我知道,但你能不能创建一个新的ClaimsIdentity?

public override async Task Invoke(IOwinContext context)
{
    var identity= new ClaimsIdentity(new List<Claim> {
        new Claim(ClaimTypes.Name, "TEST@domain.local")
    });
    var user = new ClaimsPrincipal(identity);
    context.Request.Context.Authentication.User = user;
    await Next.Invoke(context);
}
相关问题