How would you unit test a custom action filter's logic in isolation, without needing a full HTTP request pipeline?
Short answer
Construct an ActionExecutingContext (or the appropriate context type for the filter method under test) directly with test data (a mock ActionContext, ModelState, action arguments), call the filter's method directly, and assert on the resulting context.Result or other observable…
Advertisement
AModel answer
Construct an ActionExecutingContext (or the appropriate context type for the filter method under test) directly with test data (a mock ActionContext, ModelState, action arguments), call the filter's method directly, and assert on the resulting context.Result or other observable state changes -- testing the filter's logic in isolation without spinning up a full ASP.NET Core test server via WebApplicationFactory.
[Fact]
public void OnActionExecuting_SetsUnauthorizedResult_WhenApiKeyMissing() {
var httpContext = new DefaultHttpContext();
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var context = new ActionExecutingContext(actionContext, new List<IFilterMetadata>(), new Dictionary<string, object>(), null);
new ApiKeyAuthorizationFilter().OnAuthorization(new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>()));
Assert.IsType<UnauthorizedResult>(context.Result);
}Real-world example
A test suite for a custom validation action filter directly constructs the necessary context objects and calls OnActionExecuting, verifying the filter correctly short-circuits with a 400 result for invalid input without needing a full running application.
Likely follow-ups
- When would you need a full integration test instead of this isolated filter unit test?
- How do you construct a realistic ActionExecutingContext with test action arguments?
Related topics