我为 web api 编写了一个动作过滤器。如果 api 控制器中的方法抛出未处理的异常,则过滤器会创建内部错误 500 响应。
我需要知道如何测试过滤器?
我进行了广泛的研究,但无法创建合适的测试。我尝试了上下文模拟、服务定位器实现,甚至使用测试服务器进行集成测试。
Web api 控制器如下所示:
namespace Plod.Api.ApiControllers
{
[TypeFilter(typeof(UnhandledErrorFilterAttribute))]
[Route("api/[controller]")]
public class GamesController : BaseApiController
{
public GamesController(IGameService repository,
ILogger<GamesController> logger,
IGameFactory gameFactory
) : base(
repository,
logger,
gameFactory
)
{ }
// ..... controller methods are here
}
}
Run Code Online (Sandbox Code Playgroud)
在这里可以找到完整的控制器。
过滤器是这样的:
namespace Plod.Api.Filters
{
public class UnhandledErrorFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.ExceptionHandled = true;
}
} …Run Code Online (Sandbox Code Playgroud)