gpt4 book ai didi

asp.net - 如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext

转载 作者:行者123 更新时间:2023-12-02 06:16:06 25 4
gpt4 key购买 nike

假设我正在中间件中的 http 上下文上设置一个值。例如 HttpContext.User。

如何在我的单元测试中测试 http 上下文。这是我正在尝试做的示例

中间件

public class MyAuthMiddleware
{
private readonly RequestDelegate _next;

public MyAuthMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
context.User = SetUser();
await next(context);
}
}

测试

[Fact]
public async Task UserShouldBeAuthenticated()
{
var server = TestServer.Create((app) =>
{
app.UseMiddleware<MyAuthMiddleware>();
});

using(server)
{
var response = await server.CreateClient().GetAsync("/");
// After calling the middleware I want to assert that
// the user in the HttpContext was set correctly
// but how can I access the HttpContext here?
}
}

最佳答案

以下是您可以使用的两种方法:

// Directly test the middleware itself without setting up the pipeline
[Fact]
public async Task Approach1()
{
// Arrange
var httpContext = new DefaultHttpContext();
var authMiddleware = new MyAuthMiddleware(next: (innerHttpContext) => Task.FromResult(0));

// Act
await authMiddleware.Invoke(httpContext);

// Assert
// Note that the User property on DefaultHttpContext is never null and so do
// specific checks for the contents of the principal (ex: claims)
Assert.NotNull(httpContext.User);
var claims = httpContext.User.Claims;
//todo: verify the claims
}

[Fact]
public async Task Approach2()
{
// Arrange
var server = TestServer.Create((app) =>
{
app.UseMiddleware<MyAuthMiddleware>();

app.Run(async (httpContext) =>
{
if(httpContext.User != null)
{
await httpContext.Response.WriteAsync("Claims: "
+ string.Join(
",",
httpContext.User.Claims.Select(claim => string.Format("{0}:{1}", claim.Type, claim.Value))));
}
});
});

using (server)
{
// Act
var response = await server.CreateClient().GetAsync("/");

// Assert
var actual = await response.Content.ReadAsStringAsync();
Assert.Equal("Claims: ClaimType1:ClaimType1-value", actual);
}
}

关于asp.net - 如何在 ASP.NET 5/MVC 6 的单元测试中访问 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com