How to Mock Session variables in ASP.net core unit testing project?
1) I have created a mock object of a session.
Mock<HttpContext> mockHttpContext = new Mock<HttpContext>();
Mock<ITestSession> mockSession = new Mock<ISession>().As<ITestSession>();
2) Setup GetString() MEthod
mockSession.Setup(s => s.GetString("ModuleId")).Returns("1");
3) created controllerContext and assigned mockhttpContext object
controller.ControllerContext.HttpContext = mockHttpContext.Object;
4) Trying to read from a controller.
HttpContext.Session.GetString("ModuleId")
Whereas I get a null value of "ModuleId". Please help me to mock session GetString() method
Example:
//Arrange
//Note: Mock session
Mock<HttpContext> mockHttpContext = new Mock<HttpContext>();
Mock<ITestSession> mockSession = new Mock<ISession>().As<ITestSession>();
//Cast list to IEnumerable
IEnumerable<string> sessionKeys = new string[] { };
//Convert to list.
List<string> listSessionKeys = sessionKeys.ToList();
listSessionKeys.Add("ModuleId");
sessionKeys = listSessionKeys;
mockSession.Setup(s => s.Keys).Returns(sessionKeys);
mockSession.Setup(s => s.Id).Returns("89eca97a-872a-4ba2-06fe-ba715c3f32be");
mockSession.Setup(s => s.IsAvailable).Returns(true);
mockHttpContext.Setup(s => s.Session).Returns(mockSession.Object);
mockSession.Setup(s => s.GetString("ModuleId")).Returns("1");
//Mock TempData
var tempDataMock = new Mock<ITempDataDictionary>();
//tempDataMock.Setup(s => s.Peek("ModuleId")).Returns("1");
//Mock service
Mock<ITempServices> mockITempServices= new Mock<ITempServices>();
mockITempServices.Setup(m => m.PostWebApiData(url)).Returns(Task.FromResult(response));
//Mock Management class method
Mock<ITestManagement> mockITestManagement = new Mock<ITestManagement>();
mockITestManagement .Setup(s => s.SetFollowUnfollow(url)).Returns(Task.FromResult(response));
//Call Controller method
TestController controller = new TestController (mockITestManagement .Object, appSettings);
controller.ControllerContext.HttpContext = mockHttpContext.Object;
controller.TempData = tempDataMock.Object;
//Act
string response = await controller.Follow("true");
// Assert
Assert.NotNull(response);
Assert.IsType<string>(response);