Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC5: Unit Testing a controller with a session

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

like image 899
Aeterna Avatar asked Mar 16 '23 17:03

Aeterna


1 Answers

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.

like image 84
Andrei Avatar answered Mar 19 '23 05:03

Andrei