Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpActionContext.ActionArguments when testing Web.Api ActionFilter

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?

like image 238
jheppinstall Avatar asked Jun 21 '13 07:06

jheppinstall


2 Answers

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

like image 107
Duy Avatar answered Nov 10 '22 18:11

Duy


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);
like image 34
Dondee Tan Avatar answered Nov 10 '22 17:11

Dondee Tan