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 6627811
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:03:27+00:00 2026-05-25T22:03:27+00:00

How can I unit test a method which uses a session object inside of

  • 0

How can I unit test a method which uses a session object inside of its body?

Let us say I have the following action:

[HttpPost]
public JsonResult GetSearchResultGrid(JqGridParams gridParams, Guid campaignId, string queryItemsString)
{
    var queryItems = new JavaScriptSerializer().Deserialize<IList<FilledQueryItem>>(queryItemsString);
    IPageData pageData = gridParams.ToPageData();
    var extraFieldLinker = SessionHandler.CurrentExtraFieldsLinker;
    var searchParams = new SearchParamsModel(extraFieldLinker, queryItems);
    IList<CustomerSearchResultRow> searchResults = null;
    searchResults = _customerService.SearchCustomersByUrlAndCampaign(campaignId,
        searchParams.SearchString,
        searchParams.AddressFilterPredicate,
        pageData);
    return GetGridData<CustomerSearchResultGridDefinition, CustomerSearchResultRow>(searchResults, pageData);
}

I made the following unit tests which fails so far because of the session thing:

[Test]
public void CanGetSearchResultGrid()
{
    //Initialize
    var mockJqGridParams = new Mock<JqGridParams>();
    var mockPageData = new Mock<IPageData>();
    IPagedList<CustomerSearchResultRow> mockPagedResult = new PagedList<CustomerSearchResultRow>(mockPageData.Object);
    var guid= Guid.NewGuid();
    const string searchString =
        "[{\"Caption\":\"FirstName\",\"ConditionType\":\"contains\",\"Value\":\"d\",\"NextItem\":\"Last\"}]";
    Func<Address,bool> addressFilterPredicate = (x => true);

    //Setup
    mockJqGridParams.Setup(x => x.ToPageData()).Returns(mockPageData.Object);
    _customerService.Setup(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object))
        .Returns(mockPagedResult);

    //Call
    var result = _homeController.GetSearchResultGrid(mockJqGridParams.Object, guid, searchString);

    mockJqGridParams.Verify(x => x.ToPageData(), Times.Once());
    _customerService.Verify(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object)
        , Times.Once());

    //Verify
    Assert.That(result, Is.Not.Null);
    Assert.That(result, Is.TypeOf(typeof(JsonResult)));
}

And the method from the helper of course:

   public static ExtraFieldsLinker CurrentExtraFieldsLinker
    {
        get
        {
            object extraFieldLinker = GetSessionObject(EXTRA_FIELDS_LINKER);
            return extraFieldLinker as ExtraFieldsLinker;
        }
        set { SetSessionObject(EXTRA_FIELDS_LINKER, value); }
    }
  • 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-25T22:03:28+00:00Added an answer on May 25, 2026 at 10:03 pm

    I’ve solved similar issues (use of static data accessors that aren’t mock friendly – in particular, HttpContext.Current) by wrapping the access in another object, and accessing it through an interface. You could do something like:

    pubic interface ISessionData
    {
        ExtraFieldsLinker CurrentExtraFieldsLinker { get; set; }
    }
    
    public class SessionDataImpl : ISessionData
    {
        ExtraFieldsLinker CurrentExtraFieldsLinker
        {
            // Note: this code is somewhat bogus,
            // since I think these are methods of your class.
            // But it illustrates the point.  You'd put all the access here
            get { return (ExtraFieldsLinker)GetSessionObject(EXTRA_FIELDS_LINKER); }
            set { SetSessionObject(EXTRA_FIELDS_LINKER, value); }
        }
    }
    
    public class ClassThatContainsYourAction
    {
        static ClassThatContainsYourAction()
        {
            SessionData = new SessionDataImpl();
        }
    
        public static ISessionData SessionData { get; private set; }
    
        // Making this access very ugly so you don't do it by accident
        public void SetSessionDataForUnitTests(ISessionData sessionData)
        {
            SessionData = sessionData;
        }
    
        [HttpPost]
        public JsonResult GetSearchResultGrid(JqGridParams gridParams,
            Guid campaignId, string queryItemsString)
        {
            var queryItems = // ...
            IPageData pageData = // ...
    
            // Access your shared state only through SessionData
            var extraFieldLinker = SessionData.CurrentExtraFieldsLinker;
    
            // ...
        }
    }
    

    Then your unit test can set the ISessionData instance to a mock object before calling GetSearchResultGrid.

    Ideally you’d use a Dependency Injection library at some point, and get rid of the static constructor.

    If you can figure out a way to make your ISessionData an instanced object instead of static, even better. Mock object frameworks tend to like to create a new mock type for every test case, and having mocks lying around from previous tests is kind of gross. I believe session state is going to be global to your session anyway, so you might not have to do anything tricky to make a non-static object work.

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

Sidebar

Related Questions

I have to unit test a method of a groovy class which uses sleep()
I can typically test a regular Test::Unit method using the following commandline syntax for
I have the following method for which I am trying to write a unit
Let me start from definition: Unit Test is a software verification and validation method
Using shoulda with unit/test I have a context which requires one test to pass
I am trying to write a unit test for an action method which calls
I wrote an unit-test using MSTest for my Application which uses functionality from a
I have a unit test method: private bool TestCompatibility(string type1, string type2, bool shouldBeCompatible)
I have the following unit test defined to test my model binder: [TestMethod] public
Can I access HttpRuntime in my unit Test method. When I try to access

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.