Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c# - mocking session variable in unit test using Moles

Method I am unit testing checks for a session variable like

if(Session["somevar"] != null)
{
   // rest of the code
}

In my test, not able to get rid of this since Session is null, it's throwing null referrence exception.

To bypass this, I have tried mocking it like below but no luck

System.Web.Moles.MHttpContext.AllInstances.SessionGet = (HttpContext cntx) =>
{ return (HttpSessionState)cntx.Session["somevar"]; }

I even tried method mention here to simulate HttpContext and then doing below

HttpContext.Current = new HttpContext(workerRequest);
HttpContext.Current.Session["somevar"] = value;

But again no luck. This time, though the HttpContext.Current is not null but HttpContext.Current.Session and hence throws null ref exception.

Any idea how can I mock this/by pass this in my test [Without using any external DLL or main code change. Sorry, but can't afford to do so].

Thanks and appreaciate lot your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update 2013:

The bad news now is that the Moles framework was a Microsoft Research (MSR) project, and will not be supported in Visual Studio 2012. The great news is that Microsoft has now integrated the MSR project into the mainline framework as Microsoft Fakes.

I found an article that solves the problem you had, using the Fakes framework instead of the Moles framework:

http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/

Here's an updated version of my previous answer that uses the Fakes framework instead of Moles.

using System.Web.Fakes;

// ...


var sessionState = new Dictionary<string, object>();

ShimHttpContext.CurrentGet = () => new ShimHttpContext();
ShimHttpContext.AllInstances.SessionGet = (o) => new ShimHttpSessionState
{
    ItemGetString = (key) =>
    {
        object result = null;
        sessionState.TryGetValue(key, out result);
        return result;
    }
};

You might even be able to make it look more like the Moles version I posted before, though I haven't tried that out yet. I'm just adapting the article's code to my answer :)


Before 2013 edit:

You said you want to avoid changing the code under test. While I think it should be changed, as directly accessing session state like that is a bad idea, I can understand where you're coming from (I was in test once...).

I found this thread describing how someone moled both HttpContext and HttpSessionState to get around this problem.

Their code ended up looking like this:

MHttpContext.CurrentGet = () => new MHttpContext
{
    SessionGet = () => new MHttpSessionState
    {
        ItemGetString = (key) =>
        {
            if (key == "some")
                return "someString"/* or any other object*/;
            else return null;
        }
    }
};

I'd go even farther and implement ItemGetString with a dictionary:

var sessionState = new Dictionary<string, object>();

MHttpContext.CurrentGet = // ...
{
    // ...
    ItemGetString = (key) =>
    {
        object result = null;
        sessionState.TryGetValue(key, out result);
        return result;
    }

Before edit:

I usually solve problems like this by encapsulating global state with an abstract class or interface that can be instanced and mocked out. Then instead of directly accessing the global state, I inject an instance of my abstract class or interface into the code that uses it.

This lets me mock out the global behavior, and makes it so my tests don't depend on or exercise that unrelated behavior.

Here's one way to do that (I'd play with the factoring a bit tho):

public interface ISessionContext
{
    object this[string propertyName] { get; set; }
}

public class ServerContext : ISessionContext
{
    public object this[string propertyName]
    {
        get { return HttpContext.Current.Session[propertyName]; }
        set { HttpContext.Current.Session[propertyName] = value; }
    }
}

public class SomeClassThatUsesSessionState
{
    private readonly ISessionContext sessionContext;

    public SomeClassThatUsesSessionState(ISessionContext sessionContext)
    {
        this.sessionContext = sessionContext;
    }

    public void SomeMethodThatUsesSessionState()
    {
        string somevar = (string)sessionContext["somevar"];
        // todo: do something with somevar
    }
}

This would require changes to your code-under-test, but it is the type of change that is good both for testability and for portability of the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...