Owin.TestServer测试需要身份验证的中间件 [英] Owin.TestServer To Test a Middleware that Requires Authentication
问题描述
我有一个中间件方法,需要解析 context.Authentication.User.Identity.Name 才能正确执行.但是,在编写单元测试时,这些属性显然为null,因为未发生登录.我没有在此中间件中使用Oauth或任何相关的身份验证(除了明显的name属性),因为它应该在另一个中间件中的其他地方处理(以促进我正在开发的组件的重用/灵活性).有没有一种方法可以模拟/伪造此值,以便我可以运行测试?我已尝试过所有我能想到的一切来伪造登录,但是我只是停留在这一点上.为了清楚起见,中间件需要的值不是webapi调用之类的.
I have a middleware method that requires context.Authentication.User.Identity.Name to be resolved for proper execution. However, when writing a unit test these properties are obviously null as no sign-in has occurred. I am not using Oauth or anything authentication related in this middleware (beyond the obvious name property), as it should be handled elsewhere in another middleware (to promote re-use/flexibility of the component I am developing). Is there a way to mock/fake this value so I can run my test? I have tried everything I can think of to fake a sign-on and I am just stuck at this point. To be clear the middleware needs the value not a webapi call or the like.
//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.
}
推荐答案
因此,这是我不为之兴奋的一种方法,但是它确实可以完成工作.我将等待接受,因为我认为应该有更好的方法.
So here is one way I suppose not thrilled with it but it does the job. I will wait to accept as I imagine there should be a better way.
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);
}
}
这篇关于Owin.TestServer测试需要身份验证的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!