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?
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With