For my unit-tests I use Microsoft.VisualStudio.TestTools.UnitTesting
and MvcContrib.TestHelper
my action in controller:
public ActionResult index()
{
try
{
Session.Add("username", "Simon");
var lSessionID = Session.SessionID;
return Content(lSessionID);
}
catch
{
}
return Content("false");
}
my unit-test:
[TestMethod]
public void IndexTestMethod1()
{
TestControllerBuilder builder = new TestControllerBuilder();
StartController controller = new StartController();
builder.InitializeController(controller);
var lResult = controller.index();
var lReturn = ((System.Web.Mvc.ContentResult)(lResult)).Content; // returns "false"
Assert.IsFalse(lReturn == "false");
}
When I call the index()
-action in my browser, it shows the Session-ID. When I call the action via my unit-test, the lReturn
is "false"
and not the expected Session-ID.
How can I get the Session.SessionID in my unit-test?
The Session variable is read from ControllerContext.HttpContext.Session , and Session is of the type HttpSessionStateBase.
with in the unit test, you can use set the ControllerContext object. ( or use any mock providers like moq). I have not tested the code
var contextMock = new Mock<ControllerContext>();
var mockHttpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
mockHttpContext.Setup(h => h.Session).Returns(session.Object);
contextMock.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
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.