The following is a code snippet of a controller method (C #): -
public ActionResult SelectProduct(string ProdName, int Block, int ProductAddressId = 0) { if (ProductAddressId == 0 && Block == 1 && System.Web.HttpContext.Current.Session["ReturnProductAddressID"] != null) { ProductAddressId = (int)System.Web.HttpContext.Current.Session["ReturnProductAddressID"]; }
Below is the unit test method: -
[TestMethod] public void SelectProduct_Condition1_Test() { //Arrange var controller = new ProductController(); var prodName = string.Empty; var block = 1; var productAddressId = 0; //section 1 /*var mockControllerContext = new Mock<ControllerContext>(); var mockSession = new Mock<HttpSessionStateBase>(); mockSession.SetupGet(s => s["ReturnProductAddressID"]).Returns("1"); mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);*/ //section 2 /*int sessionValue = 1; var mockControllerContext = new Mock<ControllerContext>(); var mockSession = new Mock<HttpSessionStateBase>(); mockSession.SetupSet(s => s["ReturnProductAddressID"] = It.IsAny<int>()).Callback((string name, object val) => sessionValue = (int)val); mockSession.SetupGet(s => s["ReturnProductAddressID"]).Returns(() => sessionValue); mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);*/ //Act var actual = controller.SelectProduct(prodName,block,productAddressId); }
I want to ask how can I check or make fun of the value of a session value in my action method (in case)?
I tried some things in section 1 and section 2 (see the section above in the unit test method). But nothing works for this.
So can anyone let me know how to do unit test for sessions?
EDIT:
Nothing like higher than lower: -
System.Web.HttpContext.Current.Session["ReturnProductAddressID"] = "12";
means that if I set the session value directly in the unit test method. But I want to know if this will be the right approach?
c # unit-testing asp.net-mvc moq
Pawan
source share