Mocking Session not working in MVC 5 - c#

I'm storing values in the Session in my controller Action being tested. I've read several articles on how to mock a session and I'm trying to implement Milox's answer to Setting the httpcontext current session in unit test. But when I drill into Locals | this | base | HttpContext Sessions is still null and the test fails with a Null Reference exception when setting the Session variable HttpContext.Session["BsAcId"] = vM.BusAcnt.Id;
This is working production code. vM.BusAcnt.Id returns a valid int and if I substitute it with an int value the test still fails because the Session is null and therefore no value can be stored in it.
I'm using MVC5, EF6, and the latest versions of xUnit, Moq and the Resharper test runner.
Action:
public ActionResult Details(int id)
{
var vM = new BusAcntVm();
vM.BusAcnt = _db.BusAcnts.FirstOrDefault(bA => bA.Id == id);
if ((User.IsInRole("Admin"))) return RedirectToAction("Action");
HttpContext.Session["BsAcId"] = vM.BusAcnt.Id;
return View(vM);
}
MockHelpers:
public static class MockHelpers
{
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://localhost/", "");
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
return httpContext;
}
}
Test:
[Fact]
public void AdminGetBusAcntById()
{
HttpContext.Current = MockHelpers.FakeHttpContext();
var mockMyDb = MockDbSetup.MockMyDb();
var controller = new BusAcntController(mockMy.Object);
var controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.Setup( x => x.HttpContext.User.
IsInRole(It.Is<string>(s => s.Equals("Admin")))).Returns(true);
controller.ControllerContext = controllerContextMock.Object;
var viewResult = controller.Details(1) as ViewResult;
var model = viewResult.Model as BusAcntVm;
Assert.NotNull(model);
Assert.Equal("Company 1", model.CmpnyName);
}
Milox's code seems to make sense but I can't get it to work.
Have I missed something? Is there a change in MVC5 that breaks this code?
SOLUTION:
Implementation of Darin's answer. I now have a Session to write the values against (though the values don't actually get written into it, but that's not needed for the purpose of testing) and the test passes.
Test:
[Fact]
public void AdminGetBusAcntById()
{
var mockMyDb = MockDbSetup.MockMyDb();
var controller = new BusAcntController(mockMy.Object);
var context = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
var user = new GenericPrincipal(new GenericIdentity("fakeUser"), new[] { "Admin" });
context.Setup(x => x.User).Returns(user);
context.Setup(x => x.Session).Returns(session.Object);
var requestContext = new RequestContext(context.Object, new RouteData());
controller.ControllerContext = new ControllerContext(requestContext, controller);
var viewResult = controller.Details(1) as ViewResult;
var model = viewResult.Model as BusAcntVm;
Assert.NotNull(model);
Assert.Equal("Company 1", model.CmpnyName);
}

In your unit test you have set HttpContext.Current = MockHelpers.FakeHttpContext(); but ASP.NET MVC doesn't use this static property at all. Forget about HttpContext.Current in ASP.NET MVC. It's legacy and unit testing unfriendly (yes, in your case you are using it only inside your unit test, but ASP.NET MVC doesn't use it and is the reason why your code doesn't work).
The whole point is that ASP.NET MVC is working with abstractions such as HttpContextBase, HttpRequestBase, HttpResponseBase, HttpSessionStateBase, ... that you could easily mock in your unit test.
Let's take an example controller:
public class HomeController : Controller
{
public ActionResult Index()
{
if ((this.User.IsInRole("Admin")))
{
return RedirectToAction("Action");
}
this.HttpContext.Session["foo"] = "bar";
return View();
}
}
and how a corresponding unit test might look like by mocking the required abstractions using Moq:
// arrange
var controller = new HomeController();
var context = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
var user = new GenericPrincipal(new GenericIdentity("john"), new[] { "Contributor" });
context.Setup(x => x.User).Returns(user);
context.Setup(x => x.Session).Returns(session.Object);
var requestContext = new RequestContext(context.Object, new RouteData());
controller.ControllerContext = new ControllerContext(requestContext, controller);
// act
var actual = controller.Index();
// assert
session.VerifySet(x => x["foo"] = "bar");
...
And if you wanted to enter the User.IsInRole("Admin") condition, all you have to do is provide the proper role to the mocked identity.

The way, I would apply Mocking of Sessions using MOQ is as follows.
I would create a base class in UnitTests Project. Structure would be
[TestFixture]
public class BaseClass
{
public Mock<ControllerContext> controllerContext;
public Mock<HttpContextBase> contextBase;
public BaseClass()
{
controllerContext = new Mock<ControllerContext>();
contextBase = new Mock<HttpContextBase>();
controllerContext.Setup(x => x.HttpContext).Returns(contextBase.Object);
controllerContext.Setup(cc => cc.HttpContext.Session["UserId"]).Returns(1);
}
}
Please see : I am returning 1 as session value for UserId in the last line. You can change it as per the requirement.
For easy reference, I would name my TestClass as "ControllerClassTest". So I would inherit ControllerClassTest with BaseClass like this
[TestFixture]
class ControllerClassTest : BaseClass
{
}
Then, In my Test Class, I would initialize ControllerContext within Setup method like this
[SetUp]
public void Setup()
{
controller.ControllerContext = controllerContext.Object;
}
Not to forget, that we have to declare and initialize controller first.
I hope, it helps you

Related

Why does unit test for Razor Page handler return type of PartialViewResult fail?

I am using Core 3.1 Xunit to test a Razor Page in an application, with Moq to mock any services. When running a test on a handler of PageModel to test if it returns PartialViewResult type I get the following exception:
System.NullReferenceException : Object reference not set to an instance of an object.
The PageModel handler looks like this, with Application as a property on PageModel:
public PartialViewResult OnGetApplicationAddedModalPartial()
{
return Partial("_ApplicationAddedModalPartial", Application);
}
And this is the failing test for it:
[Fact]
public void OnGetApplicationAddedModalPartial_WhenCalled_ShouldReturPartialViewResultType()
{
//Arrange
_sut.Application = It.IsAny<ApplicationModel>();
//Act
var result = _sut.OnGetApplicationAddedModalPartial();
//Assert
Assert.IsType<PartialViewResult>(result);
}
What's curious is that I have another handler in that PageModel that I successfully test to see if the return is of JasonResult type. Additionally, I have controllers in this application of which some actions also return a PartialViewResult type that I successfully test for.
What is special about a handler of return type PartialViewResult on a PageModel and how can I create a test to ensure that it returns PartialViewResult?
When testing a PartialViewResult, you need to instantiate a number of properties of the PageModel as part of your setup: https://github.com/dotnet/AspNetCore.Docs/issues/24312
// Arrange
var httpContext = new DefaultHttpContext();
var modelState = new ModelStateDictionary();
var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
var modelMetadataProvider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
var pageContext = new PageContext(actionContext)
{
ViewData = viewData
};
var pageModel = new MyPageModel()
{
PageContext = pageContext,
TempData = tempData,
Url = new UrlHelper(actionContext),
MetadataProvider = modelMetadataProvider
};
// Act
var result = await pageModel.GetPartial();
// Assert
Assert.IsType<PartialViewResult>(result);

Throwing error in Unit test FormsAuthentication.SignOut()

While running my unit test method, I am getting error FormsAuthentication.SignOut(). I have mocked the httpcontext like this
var httpRequest = new HttpRequest("", "http://localhost/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer(
"id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
var controller = new AccountController();
var requestContext = new RequestContext(new HttpContextWrapper(httpContext), new RouteData());
controller.ControllerContext = new ControllerContext(requestContext, controller);
var actual = controller.Login(new CutomerModel() { Login = "admin", Password = "Password1" });
return httpContext;
in the login method
public ActionResult Login(CutomerModel obj)
{
FormsAuthentication.SignOut();
}
FormsAuthentication.SignOut(); throws
'Object reference not set to an instance of an object. '
The static method FormsAuthentication.SignOut is dependent on another static member HttpContext.Current, which is not available during unit tests. Tightly coupling your controllers to HttpContext.Current which is static results in code that is very difficult to test. Try to avoid coupling to static calls.
Side note: Having difficulty setting up a unit test for your code is a sure sign that it needs to be reviewed and most likely refactored.
Abstract FormsAuthentication calls out into their own concerns/interfaces so that they can be mocked.
public interface IFormsAuthenticationService {
void SignOut();
//...other code removed for brevity
}
Production code could wrap the actual call which should work as HttpContext.Current is then available. Make sure that DI container is aware of how to resolve the dependencies.
public class FormsAuthenticationService : IFormsAuthenticationService {
public void SignOut() {
FormsAuthentication.SignOut();
}
//...other code removed for brevity
}
Refactor the controller to depend on the abstraction and not implementation concerns.
public class AccountController : Controller {
//...other code removed for brevity.
private readonly IFormsAuthenticationService formsAuthentication;
public AccountController(IFormsAuthenticationService formsAuthentication) {
//...other arguments removed for brevity
this.formsAuthentication = formsAuthentication;
}
public ActionResult Login(CutomerModel obj) {
formsAuthentication.SignOut();
//...
return View();
}
//...other code removed for brevity.
}
And and example test
Note: I am using Moq for mocking dependencies and FluentAssertions for asserting results.
[TestMethod]
public void LoginTest() {
//Arrange
var model = new CutomerModel() { Login = "admin", Password = "Password1" };
var mockFormsAuthentication = new Mock<IFormsAuthenticationService>();
var controller = new AccountController(mockFormsAuthentication.Object);
//Act
var actual = controller.Login(model) as ViewResult;
//Assert (using FluentAssertions)
actual.Should().NotBeNull(because: "the actual result should have the returned view");
mockFormsAuthentication.Verify(m => m.SignOut(), Times.Once);
}

Testing the result of HttpResponse.StatusCode

I've written an ErrorsController that as you can imagine, has pretty simple methods to continue to serve dynamic content in the case of an error, e.g. 500.
Now what I want to do is test that in that method, HttpResponseBase.StatusCode is set to a given number while executing this method, but for some reason, the StatusCode property is always 0. This includes when examining the property directly after setting it.
Controller
public ViewResult NotFound()
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
const string PageTitle = "404 Page Not Found";
var viewModel = this.GetViewModel(PageTitle);
return this.View(viewModel);
}
GetViewModel does nothing other than setting properties on a view model
Test
[SetUp]
public void Setup()
{
this.httpContext = new Mock<HttpContextBase>();
this.httpResponse = new Mock<HttpResponseBase>();
this.httpContext.SetupGet(x => x.Response).Returns(this.httpResponse.Object);
this.requestContext = new RequestContext(this.httpContext.Object, new RouteData());
this.controller = new ErrorsController(this.contentRepository.Object);
this.controllerContext = new Mock<ControllerContext>(this.requestContext, this.controller);
this.controllerContext.SetupGet(x => x.HttpContext.Response).Returns(this.httpResponse.Object);
this.controller.ControllerContext = this.controllerContext.Object;
}
[Test]
public void Should_ReturnCorrectStatusCode_ForNotFoundAction()
{
this.controller.NotFound();
this.httpResponse.VerifySet(x => x.StatusCode = (int)HttpStatusCode.NotFound);
Assert.AreEqual((int)HttpStatusCode.NotFound, this.httpResponse.StatusCode);
}
Where am I going wrong here?
Just add this in your setup phase:
httpResponse.SetupAllProperties();
This being said, you probably don't need those 2 assertions:
this.httpResponse.VerifySet(x => x.StatusCode = (int)HttpStatusCode.NotFound);
Assert.AreEqual((int)HttpStatusCode.NotFound, this.httpResponse.StatusCode);
The first should be more than enough for your unit test.
I end up with an extension method for mocking HttpContext
public static class HttpContextExtensions
{
public static void MockHttpContext(this Controller controller)
{
var httpContextMock = new Mock<HttpContextBase>();
var requestMock = new Mock<HttpRequestBase>();
var responseMock = new Mock<HttpResponseBase>();
responseMock.SetupAllProperties();
requestMock.SetupAllProperties();
httpContextMock.Setup(x => x.Response).Returns(responseMock.Object);
httpContextMock.Setup(x => x.Request).Returns(requestMock.Object);
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = httpContextMock.Object;
}
}
Usage:
someController.MockHttpContext()

Mocking ControllerContext.IsChildAction throws exception in ParentActionViewContext

I have an ASP.Net MVC method in controller:
public ActionResult Update()
{
if(!ControllerContext.IsChildAction)
{
return RedirectToAction("Details","Project");
}
return PartialView();
}
I mock IsChildAction so it returns true.
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.SetupGet(m => m.IsChildAction).Returns(true);
YourController controller = new YourController();
controller.ControllerContext = mockControllerContext.Object;
But this change somehow reflect to asp.net mechanism which now expects property ControllerContext.ParentActionViewContext is not null. So when return statement is executed in test it throws Null reference because this property is null.
I can not mock it because it is not virtual :/
Any idea how to inject in Controller Context value for it?
You would probably have to use CallBase = true in your ControllerContext moq:
var mockControllerContext = new Mock<ControllerContext> { CallBase = true, };
This way you can still setup the IsChildAction property but with CallBase equal to true the mock of ControllerContext uses real implementation of the ControllerContext so the ParentActionViewContext should be there.
Edit:
After a short inspection of mvc-sources i guess that the Null-Reference Exception might be caused by the ParentActionViewContext which comes from: this.RouteData.DataTokens["ParentActionViewContext"] as ViewContext;.
So try to add fakeRouteData.DataTokens["ParentActionViewContext"] = fakeViewContext; to your test.
This worked for me:
[TestMethod]
public void MyTestMethod()
{
// Arrange
RouteData fakeRouteData = new RouteData();
ViewContext fakeViewContext = new ViewContext();
fakeRouteData.DataTokens["ParentActionViewContext"] = fakeViewContext;
Mock<HttpContextBase> httpContextStub = new Mock<HttpContextBase>();
RequestContext requestContext = new RequestContext(httpContextStub.Object, fakeRouteData);
HomeController controller = new HomeController();
var mockControllerContext = new Mock<ControllerContext>(requestContext, controller) { CallBase = true, };
mockControllerContext.SetupGet(m => m.IsChildAction).Returns(true);
controller.ControllerContext = mockControllerContext.Object;
// Act
var res = controller.Update();
// Assert
// TODO ...
}
Tested with System.Web.Mvc, Version=5.2.3.0.
first install this package from Package Manager Console
install-package Xania.AspNet.Simulator -Version 1.3.9
The two tests is for each execution path of the Update method.
[Test]
public void ChildActionNotInvokedAsChildAction()
{
var action = new TestController()
.Action(c => c.Update());
action.GetActionResult().Should().BeOfType<RedirectToRouteResult>();
}
[Test]
public void ChildActionInvokedAsChildAction()
{
var action = new TestController()
.ChildAction(c => c.Update());
action.GetActionResult().Should().BeOfType<PartialViewResult>();
}

Create Visual Studio Unit Tests For ASP.NET [duplicate]

I have a web service I am trying to unit test. In the service it pulls several values from the HttpContext like so:
m_password = (string)HttpContext.Current.Session["CustomerId"];
m_userID = (string)HttpContext.Current.Session["CustomerUrl"];
in the unit test I am creating the context using a simple worker request, like so:
SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;
However, whenever I try to set the values of HttpContext.Current.Session
HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";
I get null reference exception that says HttpContext.Current.Session is null.
Is there any way to initialize the current session within the unit test?
You can "fake it" by creating a new HttpContext like this:
http://www.necronet.org/archive/2010/07/28/unit-testing-code-that-uses-httpcontext-current-session.aspx
I've taken that code and put it on an static helper class like so:
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://example.com/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
return httpContext;
}
Or instead of using reflection to construct the new HttpSessionState instance, you can just attach your HttpSessionStateContainer to the HttpContext (as per Brent M. Spell's comment):
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
and then you can call it in your unit tests like:
HttpContext.Current = MockHelper.FakeHttpContext();
We had to mock HttpContext by using a HttpContextManager and calling the factory from within our application as well as the Unit Tests
public class HttpContextManager
{
private static HttpContextBase m_context;
public static HttpContextBase Current
{
get
{
if (m_context != null)
return m_context;
if (HttpContext.Current == null)
throw new InvalidOperationException("HttpContext not available");
return new HttpContextWrapper(HttpContext.Current);
}
}
public static void SetCurrentContext(HttpContextBase context)
{
m_context = context;
}
}
You would then replace any calls to HttpContext.Current with HttpContextManager.Current and have access to the same methods. Then when you're testing, you can also access the HttpContextManager and mock your expectations
This is an example using Moq:
private HttpContextBase GetMockedHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
var urlHelper = new Mock<UrlHelper>();
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var requestContext = new Mock<RequestContext>();
requestContext.Setup(x => x.HttpContext).Returns(context.Object);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("test");
request.Setup(req => req.Url).Returns(new Uri("http://www.google.com"));
request.Setup(req => req.RequestContext).Returns(requestContext.Object);
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
return context.Object;
}
and then to use it within your unit tests, I call this within my Test Init method
HttpContextManager.SetCurrentContext(GetMockedHttpContext());
you can then, in the above method add the expected results from Session that you're expecting to be available to your web service.
Milox solution is better than the accepted one IMHO but I had some problems with this implementation when handling urls with querystring.
I made some changes to make it work properly with any urls and to avoid Reflection.
public static HttpContext FakeHttpContext(string url)
{
var uri = new Uri(url);
var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
uri.Query.TrimStart('?'));
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10, true, HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
SessionStateUtility.AddHttpSessionStateToContext(
httpContext, sessionContainer);
return httpContext;
}
I worte something about this a while ago.
Unit Testing HttpContext.Current.Session in MVC3 .NET
Hope it helps.
[TestInitialize]
public void TestSetup()
{
// We need to setup the Current HTTP Context as follows:
// Step 1: Setup the HTTP Request
var httpRequest = new HttpRequest("", "http://localhost/", "");
// Step 2: Setup the HTTP Response
var httpResponce = new HttpResponse(new StringWriter());
// Step 3: Setup the Http Context
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer =
new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
// Step 4: Assign the Context
HttpContext.Current = httpContext;
}
[TestMethod]
public void BasicTest_Push_Item_Into_Session()
{
// Arrange
var itemValue = "RandomItemValue";
var itemKey = "RandomItemKey";
// Act
HttpContext.Current.Session.Add(itemKey, itemValue);
// Assert
Assert.AreEqual(HttpContext.Current.Session[itemKey], itemValue);
}
You can try FakeHttpContext:
using (new FakeHttpContext())
{
HttpContext.Current.Session["CustomerId"] = "customer1";
}
If you're using the MVC framework, this should work. I used Milox's FakeHttpContext and added a few additional lines of code. The idea came from this post:
http://codepaste.net/p269t8
This seems to work in MVC 5. I haven't tried this in earlier versions of MVC.
HttpContext.Current = MockHttpContext.FakeHttpContext();
var wrapper = new HttpContextWrapper(HttpContext.Current);
MyController controller = new MyController();
controller.ControllerContext = new ControllerContext(wrapper, new RouteData(), controller);
string result = controller.MyMethod();
In asp.net Core / MVC 6 rc2 you can set the HttpContext
var SomeController controller = new SomeController();
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
rc 1 was
var SomeController controller = new SomeController();
controller.ActionContext = new ActionContext();
controller.ActionContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
https://stackoverflow.com/a/34022964/516748
Consider using Moq
new Mock<ISession>();
The answer that worked with me is what #Anthony had written, but you have to add another line which is
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
so you can use this:
HttpContextFactory.Current.Request.Headers.Add(key, value);
Try this:
// MockHttpSession Setup
var session = new MockHttpSession();
// MockHttpRequest Setup - mock AJAX request
var httpRequest = new Mock<HttpRequestBase>();
// Setup this part of the HTTP request for AJAX calls
httpRequest.Setup(req => req["X-Requested-With"]).Returns("XMLHttpRequest");
// MockHttpContextBase Setup - mock request, cache, and session
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(ctx => ctx.Request).Returns(httpRequest.Object);
httpContext.Setup(ctx => ctx.Cache).Returns(HttpRuntime.Cache);
httpContext.Setup(ctx => ctx.Session).Returns(session);
// MockHttpContext for cache
var contextRequest = new HttpRequest("", "http://localhost/", "");
var contextResponse = new HttpResponse(new StringWriter());
HttpContext.Current = new HttpContext(contextRequest, contextResponse);
// MockControllerContext Setup
var context = new Mock<ControllerContext>();
context.Setup(ctx => ctx.HttpContext).Returns(httpContext.Object);
//TODO: Create new controller here
// Set controller's ControllerContext to context.Object
And Add the class:
public class MockHttpSession : HttpSessionStateBase
{
Dictionary<string, object> _sessionDictionary = new Dictionary<string, object>();
public override object this[string name]
{
get
{
return _sessionDictionary.ContainsKey(name) ? _sessionDictionary[name] : null;
}
set
{
_sessionDictionary[name] = value;
}
}
public override void Abandon()
{
var keys = new List<string>();
foreach (var kvp in _sessionDictionary)
{
keys.Add(kvp.Key);
}
foreach (var key in keys)
{
_sessionDictionary.Remove(key);
}
}
public override void Clear()
{
var keys = new List<string>();
foreach (var kvp in _sessionDictionary)
{
keys.Add(kvp.Key);
}
foreach(var key in keys)
{
_sessionDictionary.Remove(key);
}
}
}
This will allow you to test with both session and cache.
I was looking for something a little less invasive than the options mentioned above. In the end I came up with a cheesy solution, but it might get some folks moving a little faster.
First I created a TestSession class:
class TestSession : ISession
{
public TestSession()
{
Values = new Dictionary<string, byte[]>();
}
public string Id
{
get
{
return "session_id";
}
}
public bool IsAvailable
{
get
{
return true;
}
}
public IEnumerable<string> Keys
{
get { return Values.Keys; }
}
public Dictionary<string, byte[]> Values { get; set; }
public void Clear()
{
Values.Clear();
}
public Task CommitAsync()
{
throw new NotImplementedException();
}
public Task LoadAsync()
{
throw new NotImplementedException();
}
public void Remove(string key)
{
Values.Remove(key);
}
public void Set(string key, byte[] value)
{
if (Values.ContainsKey(key))
{
Remove(key);
}
Values.Add(key, value);
}
public bool TryGetValue(string key, out byte[] value)
{
if (Values.ContainsKey(key))
{
value = Values[key];
return true;
}
value = new byte[0];
return false;
}
}
Then I added an optional parameter to my controller's constructor. If the parameter is present, use it for session manipulation. Otherwise, use the HttpContext.Session:
class MyController
{
private readonly ISession _session;
public MyController(ISession session = null)
{
_session = session;
}
public IActionResult Action1()
{
Session().SetString("Key", "Value");
View();
}
public IActionResult Action2()
{
ViewBag.Key = Session().GetString("Key");
View();
}
private ISession Session()
{
return _session ?? HttpContext.Session;
}
}
Now I can inject my TestSession into the controller:
class MyControllerTest
{
private readonly MyController _controller;
public MyControllerTest()
{
var testSession = new TestSession();
var _controller = new MyController(testSession);
}
}
The answer #Ro Hit gave helped me a lot, but I was missing the user credentials because I had to fake a user for authentication unit testing. Hence, let me describe how I solved it.
According to this, if you add the method
// using System.Security.Principal;
GenericPrincipal FakeUser(string userName)
{
var fakeIdentity = new GenericIdentity(userName);
var principal = new GenericPrincipal(fakeIdentity, null);
return principal;
}
and then append
HttpContext.Current.User = FakeUser("myDomain\\myUser");
to the last line of the TestSetup method you're done, the user credentials are added and ready to be used for authentication testing.
I also noticed that there are other parts in HttpContext you might require, such as the .MapPath() method. There is a FakeHttpContext available, which is described here and can be installed via NuGet.
I found the following simple solution for specifying a user in the HttpContext: https://forums.asp.net/post/5828182.aspx
Never mock.. never! The solution is pretty simple. Why fake such a beautiful creation like HttpContext?
Push the session down! (Just this line is enough for most of us to understand but explained in detail below)
(string)HttpContext.Current.Session["CustomerId"]; is how we access it now. Change this to
_customObject.SessionProperty("CustomerId")
When called from test, _customObject uses alternative store (DB or cloud key value[ http://www.kvstore.io/] )
But when called from the real application, _customObject uses Session.
how is this done? well... Dependency Injection!
So test can set the session(underground) and then call the application method as if it knows nothing about the session. Then test secretly checks if the application code correctly updated the session. Or if the application behaves based on the session value set by the test.
Actually, we did end up mocking even though I said: "never mock". Becuase we couldn't help but slip to the next rule, "mock where it hurts the least!". Mocking huge HttpContext or mocking a tiny session, which hurts the least? don't ask me where these rules came from. Let us just say common sense. Here is an interesting read on not mocking as unit test can kills us
Try this way..
public static HttpContext getCurrentSession()
{
HttpContext.Current = new HttpContext(new HttpRequest("", ConfigurationManager.AppSettings["UnitTestSessionURL"], ""), new HttpResponse(new System.IO.StringWriter()));
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true,
HttpCookieMode.UseCookies, SessionStateMode.InProc, false));
return HttpContext.Current;
}

Categories

Resources