在没有公共构造函数的情况下模拟密封类?
我正在测试的特定类取决于 HttpSessionState 对象。
HttpSessionState 类没有公共构造函数。被测试的类仅使用该对象作为 NameValue 存储。该类在 ASMX Web 服务中用于返回特定方法的信息。
我正在考虑围绕 HttpSessionState 类创建一个外观,在其中我可以提供一个字典
这是一个好主意还是标准做法?
The particular class I'm testing depends upon the HttpSessionState object.
The HttpSessionState class has no public constructors. The class under test is only using this object as a NameValue store. The class is used in an ASMX web service to return information for a particular method.
I'm thinking about creating a facade around the HttpSessionState class where I can provide a Dictionary <string, string> instead of the Session object in testing.
Is this a good idea or standard practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,正如老话所说,没有什么是通过添加另一层抽象不能解决的。我通常只是将类型隐藏在接口后面,其中接口的方法是对该类型执行我想要的操作的唯一方法。
只需模拟隐藏 HttpSessionState 的接口,并对接口的使用进行断言,在 Rhino Mocks 中,它只是 AssertWasCalled(d => ....) 等。
Yep, as the old saying goes, there's nothing that can't be solved by adding another layer of abstraction. I usually just hide the type behind an interface where the interface's methods are the only ones needed to perform the actions I want on that type.
Just mock the interface that hides HttpSessionState, and do Asserts on the uses of the interface, in Rhino Mocks it's just AssertWasCalled(d => ....) etc.
您可以创建 HttpSessionStateBase 类的子类。 这个答案展示了如何为 Moq 实现这一点,但您仍然可以将 MockHttpSession 类与您的 Rhino Mocks 一起使用(我假设。我没有使用过Rhino Mocks)。
关于如何模拟 .NET 类的相当广泛的讨论可以在 Scott Hanselman 的博客此处。
You can create a sub-class of the HttpSessionStateBase class. This answer shows how to implement this for Moq, but you can still use the MockHttpSession class with your Rhino Mocks (I assume. I haven't used Rhino Mocks).
A fairly extensive discussion about how to mock .NET classes can be found at Scott Hanselman's blog here.
您可以使用 Microsoft 的 .NET Moles 隔离框架来模拟任何类型,甚至是密封类型。设置需要一些工作,但可能比添加另一层抽象更好。 此处讨论了使用摩尔模拟
HttpContext
和HttpSessionState
。 此处还有另一个类似的讨论。You can mock any type even sealed ones using Microsoft's Moles Isolation framework for .NET. Takes a little work to setup but might be better than adding another layer of abstraction. Mocking
HttpContext
andHttpSessionState
using moles is discussed here. There is another similar discussion here.