单元测试自己的中间件,它设置查询字符串
本文关键字:设置 查询 字符串 自己的 中间件 单元测试 | 更新日期: 2023-09-27 17:54:14
我有一个自己的中间件,它检查查询字符串中的特定值,并更新查询字符串中的另一个值。我使用Microsoft.OWin.Testing来调用这个中间件,然后发出请求。我如何准确地检查查询字符串在我发出请求后被更改。
public static void UseInjectQueryString(this IAppBuilder app)
{
app.Use(async (context, next) =>
{
// Some code here
if (context.Environment.ContainsKey("owin.RequestQueryString"))
{
var existingQs = context.Environment["owin.RequestQueryString"];
var parser = new UrlParser(existingQs.ToString());
parser[Constants.AuthorizeRequest.AcrValues] = newAcrValues;
context.Environment.Remove("owin.RequestQueryString");
context.Environment["owin.RequestQueryString"] = parser.ToString();
}
}
await next();
});
单元测试:
[TestMethod]
public async Task SomeTest()
{
using (var server = TestServer.Create(app =>
{
//.... injecting middleware..
}))
{
HttpResponseMessage response = await server.CreateRequest("core/connect/token?client_id=clientStub").GetAsync();
}
}
我会重构中间件,以便您可以在管道之外对其进行测试。例如,您可以这样构建它:
public static class InjectQueryStringMiddleware
{
public static void InjectQueryString(IOwinContext context)
{
if (context.Environment.ContainsKey("owin.RequestQueryString"))
{
var existingQs = context.Environment["owin.RequestQueryString"];
var parser = new UrlParser(existingQs.ToString());
parser[Constants.AuthorizeRequest.AcrValues] = newAcrValues;
context.Environment.Remove("owin.RequestQueryString");
context.Environment["owin.RequestQueryString"] = parser.ToString();
}
}
public static void UseInjectQueryString(this IAppBuilder app)
{
app.Use(async (context, next) =>
{
// some code here
InjectQueryString(context);
}
}
}
现在可以测试InjectQueryString
,并且它对上下文做了正确的事情,而不必创建整个管道。