How to test custom action filter in ASP.NET Core?
The only way I was able to do this was by creating bare-boned concrete classes and testing the HTTPContext result for what I wanted to achieve. Since I was using concrete classes there was no need for Mock
The setup:
[SetUp]
public void SetUp()
{
_actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
RouteData = new RouteData(),
ActionDescriptor = new ActionDescriptor()
};
}
The test:
[Test]
public void Should_deny_request()
{
// Given
var resourceExecutingContext = new ResourceExecutingContext(_actionContext, new List<IFilterMetadata>(), new List<IValueProviderFactory>());
var attribute = new YourAttribute();
// When
attribute.OnResourceExecuting(resourceExecutingContext);
var result = (ContentResult) resourceExecutingContext.Result;
// Then
Assert.IsTrue(Equals("403", result.StatusCode.ToString()));
}
And this worked for me.