简体   繁体   中英

“Faking” Session variable(HttpSessionstateBase) of the controller in asp.net mvc

I am presently working on unit testing using Microsoft Fakes and testing a controller which uses some session variables. Since no session is being initiated during unit test creation whenever I'm running unit test I'm stuck with a NullReferenceException.I have seen many question and answers doing it using Moqs but I want it in Microsoft Fakes. I know I need to use shims to fake session variable ,since I'm not having a clear idea about how exactly session is being created I'm stuck there. Please explain me how exactly a session is created so that I can fake it,also if possible please let me know how to write it in microsoft fakes

Well, you can this as example :

public class SomeClass
{
    public bool SomeMethod()
    {
        var session = HttpContext.Current.Session;
        if (session["someSessionData"].ToString() == "OK")
            return true;
        return false;               
    }
}

[TestMethod]
public void SomeTestMethod()
{
    using (ShimsContext.Create())
    {
        var instanceToTest = new SomeClass();

        var session = new System.Web.SessionState.Fakes.ShimHttpSessionState();
        session.ItemGetString = (key) => { if (key == "someSessionData") return "OK"; return null; };

        var context = new System.Web.Fakes.ShimHttpContext();
        System.Web.Fakes.ShimHttpContext.CurrentGet = () => { return context; };
        System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet =
            (o) =>
            {
                return session;
            };

        var result = instanceToTest.SomeMethod();
        Assert.IsTrue(result);
    }
}

Please see http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/ for more details. Have a nice day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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