1

I'm trying to write unit tests for my actions, but I am unable to find a way to check authorization. My first attempt is based on the accepted answer in this thread:

    [Test]
    public void Test()
    {
        var request = new Mock<HttpRequestBase>();
        request.SetupGet(x => x.IsAuthenticated).Returns(false);

        var context = new Mock<HttpContextBase>();
        context.SetupGet(x => x.Request).Returns(request.Object);

        var controller = new HomeController();
        controller.ControllerContext =
               new ControllerContext(context.Object, new RouteData(), controller);

        // test
        ViewResult viewResult = (ViewResult)controller.Index();

        Assert.True(viewResult.ViewName == "Logon");
    }

However, viewResult.ViewName is "Home" even though I am mocking IsAuthenticated as false.

HomeController:

[Authorize]
public class HomeController : ApplicationController
{
    public ActionResult Index()
    {
        return View("Home");
    }
   ...
}
Kev
  • 2,656
  • 3
  • 39
  • 63
  • 1
    Authorization is something that happens in the pipeline. The way you are trying to test it wont work. You would need to do an integration test – Nkosi Dec 13 '16 at 13:28
  • @Nkosi then why was it an accepted answer in the other thread? – Kev Dec 13 '16 at 15:56
  • Because in that case the OP was probably doing something like `if(Request.IsAuthenticated) { return View("Home"); } else { ... }` within the method, not testing Authorized attribute. – Nkosi Dec 13 '16 at 15:58
  • @Nkosi I was thinking that you could invoke the action and check the result == NotAuthorizedResult. Not sure how. I have read other threads saying testing [Authorize] isn't required since it is assumed to work correctly, and that you should test only your actions, ignoring authorization. – Kev Dec 13 '16 at 16:25
  • I hope this link helps :-) I meant this link http://stackoverflow.com/questions/669175/unit-testing-asp-net-mvc-authorize-attribute-to-verify-redirect-to-login-page (sorry my pasting) – jyrkim Dec 13 '16 at 18:13

0 Answers0