jhe*_*all 7 c# unit-testing mocking asp.net-web-api
我正在编写一个OnActionExecuting操作过滤器,我想对功能进行单元测试.
过滤器需要做的一件事是对传递给过滤器的动作参数执行一些验证.
我从actionContext.ActionArguments
字典中得到的参数对于实现工作正常,但我很难设法对它进行单元测试.
在我的测试中,我无法设置,actionContext.ActionArguments
因为它没有setter,也不能嘲笑它,因为它不是虚拟的.
这让我有点陷入困境,我是否能在这种情况下从单元测试中获得任何价值?
Duy*_*Duy 11
根据AspNetWebStack源代码,actionContext.ActionArguments只是一个简单的Dictionary.因此,在其中插入键值对非常简单.我会做类似的事情
actionContext.ActionArguments [key] = value;
在单元测试的安排部分.
希望有所帮助
小智 6
请访问我的博客: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);
Run Code Online (Sandbox Code Playgroud)