如何伪造ResultExecutionDelegate来对IAsyncResultFilter进行单元测试



在测试我的IAsyncResultFilter时,我知道如何为OnResultExecutionAsync创建ResultExecutingContext,但我不知道应该如何创建ResultExecutionDelegate参数。

public class JsonPrefixFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)

我试着这样指定我的代表:

ResultExecutionDelegate next = () => {
var response = executed.HttpContext.Response;
response.Headers["Content-Type"] = "application/json";
response.Body.Write(Encoding.UTF8.GetBytes("{}"));
return Task.FromResult(executed);
};

但是,当过滤器运行时,在调用await next();之后,响应没有我指定的内容类型或正文。

使用委托语法创建委托的实例,并像任何其他变量一样将其传递给被测试对象的调用。

//Arrange
HttpContext http = new DefaultHttpContext();
ResultExecutingContext executing = CreateResultExecutingContext(http); //local
ResultExecutedContext executed = CreateResultExecutedContext(http); //local
ResultExecutionDelegate next = () => {
//... do something
var response = executed.HttpContext.Response;
response.Headers["Content-Type"] = "application/json";
response.Body = new MemoryStream(Encoding.UTF8.GetBytes("{}"));
return Task.FromResult(executed);
};
var filter = new JsonPrefixFilter();
//...
//Act
await filter.OnResultExecutionAsync(executing, next);
//Assert
//...

其中辅助方法定义为

private static ActionContext CreateActionContext(HttpContext context) => new(context, new(), new());
private static ResultExecutedContext CreateResultExecutedContext(HttpContext context) => 
new ResultExecutedContext(CreateActionContext(context), Array.Empty<IFilterMetadata>(), new NoOpResult(), new());
private static ResultExecutingContext CreateResultExecutingContext(HttpContext context) => 
new ResultExecutingContext(CreateActionContext(context), Array.Empty<IFilterMetadata>(), new NoOpResult(), new object());

相关内容

  • 没有找到相关文章

最新更新