如何测试与工作的ModelState ActionFilterAttributes? [英] How do I test ActionFilterAttributes that work with ModelState?
问题描述
正如所建议的(等等)卡子门祖尔拉希德在这个博客帖子,我使用 ActionFilterAttributes
来重定向时模型的状态从一个请求传输到另一个。
As suggested by (among others) Kazi Manzur Rashid in this blog post, I am using ActionFilterAttributes
to transfer model state from one request to another when redirecting.
不过,我发现自己不能写一个单元测试,测试这些属性的行为。作为一个例子,这就是我想要用于测试的 ImportModelStateAttribute
来做到:
However, I find myself unable to write a unit test that test the behavior of these attributes. As an example, this what I want the test for the ImportModelStateAttribute
to do:
- 设置的
filterContext
让的TempData [的myKey]
包含了一些假冒出口ModelState中
(即一个ModelStateDictionary
创建自己,添加一个错误) - 请
的ModelState
包含一个模型误差。 - 呼叫
OnActionExecuting
。 - 确认两个字典合并,而
的ModelState
现在包含的两个的错误。
- Setup the
filterContext
so thatTempData[myKey]
contains some fake "exported"ModelState
(that is, aModelStateDictionary
I create myself, and add one error to) - Make
ModelState
contain one model error. - Call
OnActionExecuting
. - Verify the two dictionaries are merged, and
ModelState
now contains both errors.
我在的第一步已经出现亏损。
I'm at a loss already on the first step.
编辑:结果
是的,我已经试过嘲弄 ActionFilterAttribute
与起订量,但我得到的错误,指出
Yes, I've tried mocking ActionFilterAttribute
with Moq, but I get errors stating
在非覆盖的成员设置无效
Invalid setup on non-overridable member
为的TempData code>和
的ModelState
。
推荐答案
托马斯,你不必嘲笑filterContext,可以用于测试操作筛选器创建实际的对象,同样也适用于模型的状态,这些都是POCO的对象。只有你所嘲笑的事情是HttpContext的(如果需要)。
Tomas, You do not have to mock the filterContext, you can create the real object for testing the action filter, the same goes for the model state, these are poco objects. Only thing that you have to mock is the HttpContext (if needed).
[Fact]
public void Should_import_complete_view_data()
{
var attribute = new ImportViewDataFromTempDataAttribute();
var httpContext = new Mock<HttpContextBase>();
var requestContext = new RequestContext(httpContext.Object, new RouteData());
var previousModel = new object();
var previousViewData = new ViewDataDictionary(previousModel) {{"foo", "bar"}};
previousViewData.ModelState.AddModelError("foo", "bar");
var controller = new Mock<ControllerBase>();
controller.Object.ViewData = new ViewDataDictionary();
controller.Object.TempData = new TempDataDictionary { { attribute.Key, previousViewData } };
var controllerContext = new ControllerContext(requestContext, controller.Object);
var actionContext = new ActionExecutingContext(controllerContext, new Mock<ActionDescriptor>().Object, new Dictionary<string, object>());
attribute.OnActionExecuting(actionContext);
Assert.True(actionContext.Controller.ViewData.ContainsKey("foo"));
Assert.True(actionContext.Controller.ViewData.ModelState.ContainsKey("foo"));
Assert.Same(previousModel, actionContext.Controller.ViewData.Model);
}
这篇关于如何测试与工作的ModelState ActionFilterAttributes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!