有没有办法(单位)测试我自己的HtmlHelpers?如果我想要自定义控件(由HtmlHelper呈现),并且我知道该控件的请求如何首先编写测试 – 然后编写代码?有没有一个特定的(好)的方法来做到这一点?
这值得吗?
解决方法
主要的问题是您必须模拟HtmlHelper,因为您可能正在使用帮助程序的方法来获取路由或值或返回另一个扩展方法的结果。 HtmlHelper类有很多属性,其中一些类似于ViewContext或当前Controller的复杂性。
This post from Ben Hart解释了如何用Moq创建这样的模拟。可以轻松地翻译成另一个模拟框架。
这是我的Rhino Mocks版本,适合于MVC框架中的变化。它没有完全测试,但它是为我工作,但不期望完美的结果:
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData) { var mocks = new MockRepository(); var cc = mocks.Dynamicmock<ControllerContext>( mocks.Dynamicmock<HttpContextBase>(),new RouteData(),mocks.Dynamicmock<ControllerBase>()); var mockViewContext = mocks.Dynamicmock<ViewContext>( cc,mocks.Dynamicmock<IView>(),viewData,new TempDataDictionary()); var mockViewDataContainer = mocks.Dynamicmock<IViewDataContainer>(); mockViewDataContainer.Expect(v => v.ViewData).Return(viewData); return new HtmlHelper(mockViewContext,mockViewDataContainer); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。