使用自定义模型绑定器对控制器进行单元测试
在我的应用程序中,我有一个自定义模型绑定程序,我将其设置为 global.asax 中的 DefaultBinder:
ModelBinders.Binders.DefaultBinder = new XLDataAnnotationsModelBinder();
在为控制器编写单元测试时,我需要确保控制器使用自定义模型绑定程序,但我不知道如何执行此操作。
我的测试如下所示:
[Test]
public void Details_Post_Action_Fails_To_Change_Email_Address_With_Duplicate()
{
// Setup
var controller = new AccountController();
controller.SetFakeControllerContext();
var param = Customer.Load(30005);
param.EmailAddress = "[email protected]";
// Test
var result = controller.Details(param);
// Assert
Assert.IsTrue(result is ViewResult); // will be ViewResult if failed....
Assert.IsFalse(((ViewResult)result).ViewData.ModelState.IsValid);
}
通过此单元测试,控制器最终使用 DefaultModelBinder。我可以在此测试中添加什么来确保控制器使用自定义模型绑定器?
In my application I have a custom model binder that I set to the DefaultBinder in the global.asax:
ModelBinders.Binders.DefaultBinder = new XLDataAnnotationsModelBinder();
When writing unit tests for controllers I need to make sure the controller uses the custom model binder but I don't know how to do this.
My test looks like this:
[Test]
public void Details_Post_Action_Fails_To_Change_Email_Address_With_Duplicate()
{
// Setup
var controller = new AccountController();
controller.SetFakeControllerContext();
var param = Customer.Load(30005);
param.EmailAddress = "[email protected]";
// Test
var result = controller.Details(param);
// Assert
Assert.IsTrue(result is ViewResult); // will be ViewResult if failed....
Assert.IsFalse(((ViewResult)result).ViewData.ModelState.IsValid);
}
With this unit test the controller ends up using the DefaultModelBinder. What can I add in this test to ensure the controller uses the custom model binder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scott Hanselman 不久前发表了一篇与此相关的博客文章:
Splitting DateTime - Unit Test ASP.NET MVC自定义模型绑定器
您感兴趣的部分位于帖子底部的“测试自定义模型绑定器”下。基本上,您实例化一个 ModelBindingContext,然后实例化您的 Modelbinder 并在您的 Modelbinder 上调用 Bind(),传入您创建的 ModelBindingContext(以及控制器上下文,如果需要)。
这是 SO 的另一个问题,也包含您需要的信息(即使您没有使用起订量):
如何使用 Moq 对自定义 ModelBinder 进行单元测试?
Scott Hanselman made a blog post related to this a while ago:
Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders
The part that would interest you is at the bottom of the post under "Testing the Custom Model Binder". Basically you instantiate a ModelBindingContext, then instantiate your Modelbinder and call Bind() on your Modelbinder passing in the ModelBindingContext you created (and the controller context if required).
Here is another question at SO that also contains the information you need (even if you're not using Moq):
How to Unit Test a custom ModelBinder using Moq?