Mukund Katpatal
Mukund Katpatal

Reputation: 41

How to unit test exception filter in web API ASP.Net core. Dont want to mock the onException method

How to unit test exception filter in web API ASP.Net core. Don't want to mock the onException method. I have mocked ControllerContext like below in my unit tests. Class libraries which are called from the Web API throw custom exceptions which are caught by exception filters and I want to unit test that. Today I get "Value does not fall within the expected range" error.

    public static ControllerContext GetMockControllerContext(
        this Controller controller,
        RouteData routeData)
    {

        var actionContext = new ActionContext
        {
            HttpContext = new DefaultHttpContext
            {
                User = controller.GetMockUserContext()
            },
            RouteData = routeData,
            ActionDescriptor = new ControllerActionDescriptor()
        };
        return new ControllerContext(actionContext);
    }

Upvotes: 4

Views: 4280

Answers (1)

ssmith
ssmith

Reputation: 8922

I would write an integration test using TestServer as covered in the documentation. It will run about as fast as an actual unit test but will be much more valuable as it will demonstrate your filter working within the actual MVC context/pipeline.

Upvotes: 5

Related Questions