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.