8

I am writing an OnActionExecuting action filter and I want to unit test the functionality.

One of the things the filter needs to do is to performs some validation on the action arguments passed into the filter.

I am getting the arguments from the actionContext.ActionArguments Dictionary which is working fine for the implementation but I am having a difficult time managing to unit test it.

In my test I cannot set actionContext.ActionArguments as it has no setter an nor can I mock it as it is not virtual.

This leaved me in a bit of a quandary as to whether I can get any value from unit tests in this scenario?

2 Answers 2

12

According to the AspNetWebStack source code, actionContext.ActionArguments is just a simple Dictionary. It is therefore pretty trivial to insert a key value pair into it. I would just do something like

actionContext.ActionArguments[key] = value;

in the arrange part of the unit test.

Hope that helps

Sign up to request clarification or add additional context in comments.

Comments

6

See my blog for this: https://dondeetan.com/2016/09/19/validating-and-unit-testing-web-api-2-route-attribute-parameters/

 var mockactioncontext = new HttpActionContext
            {
                ControllerContext = new HttpControllerContext
                {
                    Request = new HttpRequestMessage()
                },
                ActionArguments = { { "employeeid", "null" } }
            };

            mockactioncontext.ControllerContext.Configuration = new HttpConfiguration();
            mockactioncontext.ControllerContext.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

            var filter = new <youractionattributefilterclass>();
            filter.OnActionExecuting(mockactioncontext);
            Assert.IsTrue(mockactioncontext.Response.StatusCode == HttpStatusCode.BadRequest);

2 Comments

Do you know why not an instance of Dictionary<string, object> can be passed to ActionArguments? It fails for me and says ActionArguments is read-only.
Sorry late response. Haven't try that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.