如何测试在ASP.NET MVC中的自定义模型绑定? [英] How to test custom Model Binders in ASP.NET MVC?

查看:109
本文介绍了如何测试在ASP.NET MVC中的自定义模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的ASP.NET MVC应用程序编写一些自定义模型粘合剂(实施IModelBinder)。我想知道什么是单元测试他们一个很好的方法(粘合剂)?

I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?

推荐答案

我这样做的:

var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };         
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();           

var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);



private static ControllerContext GetControllerContext(NameValueCollection form) {
    Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
    mockRequest.Expect(r => r.Form).Returns(form);

    Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
    mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);

    return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
}

然后,我刚才在的BindingContext变量传递到实现IModelBinder接口的对象的BindModel方法。

And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.

这篇关于如何测试在ASP.NET MVC中的自定义模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆