Mocking sealed classes without public constructors?

房东的猫 提交于 2019-12-22 05:39:29

问题


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?


回答1:


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.




回答2:


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).

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.




回答3:


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 and HttpSessionState using moles is discussed here. There is another similar discussion here.



来源:https://stackoverflow.com/questions/9155454/mocking-sealed-classes-without-public-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!