1

我有一个中间件方法,需要解析context.Authentication.User.Identity.Name才能正确执行。但是,在编写单元测试时,这些属性显然为空,因为没有发生登录。我没有在这个中间件中使用 Oauth 或任何相关的身份验证(除了明显的 name 属性),因为它应该在另一个中间件的其他地方处理(以促进我正在开发的组件的重用/灵活性)。有没有办法模拟/伪造这个值,以便我可以运行我的测试?我已经尝试了我能想到的一切来伪造登录,但我只是停留在这一点上。要清楚中间件需要的值不是 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.
}
4

2 回答 2

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);
    }
}
于 2016-03-14T20:05:25.820 回答
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);
}
于 2016-07-05T13:47:32.067 回答