简体   繁体   English

没有公共建设者的模拟密封课程?

[英]Mocking sealed classes without public constructors?

The particular class I'm testing depends upon the HttpSessionState object. 我正在测试的特定类依赖于HttpSessionState对象。

The HttpSessionState class has no public constructors. HttpSessionState类没有公共构造函数。 The class under test is only using this object as a NameValue store. 被测试的类仅将此对象用作NameValue存储。 The class is used in an ASMX web service to return information for a particular method. 该类在ASMX Web服务中用于返回特定方法的信息。

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. 我正在考虑在HttpSessionState类周围创建一个Facade,我可以在测试中提供Dictionary <string,string>而不是Session对象。

Is this a good idea or standard practice? 这是一个好主意还是标准做法?

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. 只是模拟隐藏HttpSessionState的接口,并对接口的使用做Asserts,在Rhino Mocks中它只是AssertWasCalled(d => ....)等。

You can create a sub-class of the HttpSessionStateBase class. 您可以创建HttpSessionStateBase类的子类。 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). 这个答案显示了如何为Moq实现这个,但你仍然可以将MockHttpSession类与你的Rhino Mocks一起使用(我假设。我没有使用过Rhino Mocks)。

public class MockHttpSession : HttpSessionStateBase
{
    Dictionary<string, object> sessionStorage = new Dictionary<string, object>();

    public override object this[string name]
    {
        get { return sessionStorage[name]; }
        set { sessionStorage[name] = value; }
    }
}

A fairly extensive discussion about how to mock .NET classes can be found at Scott Hanselman's blog here . 关于如何模拟.NET类的相当广泛的讨论可以在Scott Hanselman的博客上找到

You can mock any type even sealed ones using Microsoft's Moles Isolation framework for .NET . 您可以使用Microsoft的Moles Isolation框架来模拟任何类型甚至密封的类型。 Takes a little work to setup but might be better than adding another layer of abstraction. 需要做一些设置,但可能比添加另一层抽象更好。 Mocking HttpContext and HttpSessionState using moles is discussed here . 这里讨论使用moles模拟HttpContextHttpSessionState There is another similar discussion here . 还有另外一个类似的讨论在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM