如何测试asp.net服务器控件
我们已经开发了许多 ASP.Net 服务器控件,我们需要测试它们。 我想实例化一个控件,设置一些属性,调用 CreateChildControls 并测试控件层次结构。
我遇到了许多问题:
- 控件依赖于 HttpContext
- CreateChildControls 是私有的
即使将单个子控件添加到控件集合中也会调用依赖于 HttpContext 的 ResolveAdapter() 方法。
我该如何解决这个问题?
ps 我不想测试页面上的控件(!)。
We have developed a number of ASP.Net server controls and we need to test them. I want to instantiate a control, set some properties, call CreateChildControls and test the control-hierarchy.
I run into a number of problems:
- The controls rely on HttpContext
- CreateChildControls is private
Even adding a single child control to the controls collection calls the ResolveAdapter() method which relies on HttpContext.
How can I get around this?
p.s. I do not wish to test the controls on a page (!).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来很像您根本不关心控件的实际呈现,而是关心控件中包含的逻辑。 为此,我建议您除了无法在 HttpContext 之外测试控件之外还有另一个问题。
如果逻辑仅与控件有关,那么您应该信任框架来完成其工作,并将控件放在页面上以查看其是否正常工作。 如果您尝试测试的逻辑是业务逻辑,那么您需要重构。
将业务逻辑提取到某个单独的项目/Dll 中,并考虑实现 MVP 模式 与您的服务器控制。 您也不必使用像 WCSF 这样的大型重型框架。 从概念上讲,您可以毫不费力地实现这一点。
创建一个代表视图上的值的接口:
后,您需要一个演示器来执行此视图:
现在您的服务器控件可以实现此接口,并使用
OrderPresenter
初始化自身定义 有它! 您现在应该能够使用已存根的视图针对 OrderPresenter 编写单元测试。 不需要 HttpContext,并且您可以更清晰地分离关注点。
如果您已经将所有业务逻辑分开,那么我表示歉意,但除了需要验证实际业务逻辑之外,我想不出在 ASP.Net 运行时之外测试服务器控件的任何其他原因。 如果是这种情况,那么我强烈建议您在意识到这最终会导致维护噩梦之前立即重构 泄漏抽象。
It sounds a lot like you don't care about the actual rendering of the control at all, but rather the logic contained within the control. For that I would suggest that you have another problem besides the inability to test the control outside the HttpContext.
If the logic only pertains to the control, then you should trust the framework to do it's job, and drop the control on a page to see if it works properly. If the logic you are attempting to test is business logic, then you need to refactor.
Pull out the business logic into a seperate Project/Dll somewhere, and think about implementing a MVP pattern with your server control. You don't have to go with a big heavy framework like WCSF either. Conceptually you can implement this with little effort.
Create an interface that represents the values on your view:
Once this is defined, you need a presenter that exercises this view:
Now your server control can implement this interface, and initialize itself with the
OrderPresenter
And there you have it! You should be able to write unit tests against the OrderPresenter now using a stubbed out View. No HttpContext required, and you have cleaner seperation of concerns.
If you already have all your business logic seperated out then I appologize, but I can't think of any other reason to test a server control outside the ASP.Net runtime besides needing to verify actual business logic. If this is the case, then I would highly encourage you to refactor now before you realize the maintenance nightmare this will eventually cause via Leaky Abstractions.