I have read many blogs and comments about Mocking a session object or using a fake objects, but i still cannot translate those answers to my own code.
Here is the Index Action of my UserController, that uses dependency injection to inject a IUserRepository into the constructor:
// GET: User
public ActionResult Index()
{
User user = (User) Session["CurrentUser"];
if (user != null) {
if(_repository.UserHasAdminAcces(user))
return View(_repository.GetAllUsers().ToList());
return RedirectToAction("DisplayErrorPage", "Error", new { errorMessage = "You have to be an Admin to enter this part" });
}
return RedirectToAction("Login");
}
My Test Method currently looks like this:
public void TestIndexForValidUser()
{
var mock = new Mock<IUserRepository>();
mock.Setup(x => x.UserHasAdminAcces(It.IsAny<User>())).Returns(true);
UserController target = new UserController(mock.Object);
// create mock HttpContext
var context = new Mock<ControllerContext>();
target.ControllerContext = context.Object;
var result = target.Index() as ViewResult;
Assert.AreEqual(result, "Index");
}
I want to give the ControllerContext a session object that returns a fake user and make sure that a View called Index is returned
I use this approach:
var controller = new HomeController();
var context = MockRepository.GenerateStub<ControllerContext>();
context.Expect(x => x.HttpContext.Session["MyKey"]).Return("MyValue");
controller.ControllerContext = context;
See ScottGu's blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With