Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6944787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T13:21:09+00:00 2026-05-27T13:21:09+00:00

Method I am unit testing checks for a session variable like if(Session[somevar] != null)

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T13:21:10+00:00Added an answer on May 27, 2026 at 1:21 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have 1 unit test method that needs several parameters. I would like to
I want to Unit-test a method like the following: public ActionResult StoreFile(FormCollection form, string
I've got a WCF REST Service which I'd like to unit test. i.e -
In unit testing, the setup method is used to create the objects needed for
I'm having trouble unit testing a method that changes some properties of a reference
I am starting out with unit testing, I have a method that uses the
Should one create unit tests involving IO? Ie, testing a class method for serializing/deserializing
I can typically test a regular Test::Unit method using the following commandline syntax for
I'm writing a unit test for a method that packs boolean values into a
I need to write a unit test for a method that will print a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.