Mocking session variables using Moq

by sunil ravulapalli /22. March 2013 00:20 /.net-tools /Comments (0)

If we want to test a controller method which uses session variables like the following example, we can use the Moq library to Mock up the session variables.

 
public ActionResult ShowBalance()
{
  var accountId = Convert.ToInt64(Session[SessionConstants.AccountId]);
  var last4DigitsOfSsn = Session[SessionConstants.Last4DigitsOfSsn].ToString();
  AccountStatus accountStatus = _quickPayService.ValidateAccount(accountId, last4DigitsOfSsn);
  if (accountStatus.IsValid)
    return View(accountStatus);
  else
    return RedirectToAction("ShowError", accountStatus );
}

Below is an example of how session variables can be mocked

[TestMethod]
public void ShowBalance_WithNonExistantAccount_GoesToShowError()
{
  //Arrange
  Mock<HttpSessionStateBase> session = new Mock<HttpSessionStateBase>();
  session.SetupGet(s => s["AccountId"]).Returns(99999999);
  session.SetupGet(s => s["Last4DigitsOfSsn"]).Returns("9999");
Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(); httpContext.SetupGet(c => c.Session).Returns(session.Object);
ControllerContext ctx = new ControllerContext(); ctx.HttpContext = httpContext.Object;
var quickPayServiceMock = new Mock<IQuickPayService>(); quickPayServiceMock.Setup(quickpayservice => quickpayservice.ValidateAccount(99999999, "9999")).Returns(new AccountStatus { IsValid = false }); KioskController controller = new KioskController(quickPayServiceMock.Object); controller.ControllerContext = ctx; //Act RedirectToRouteResult redirectToRouteResult = controller.ShowBalance() as RedirectToRouteResult; //Assert Assert.AreEqual("ShowError", redirectToRouteResult.RouteValues["action"].ToString()); }
blog comments powered by Disqus