How do I unit test a controller method that has the [Authorize] attribute applied?

后端 未结 1 1811
感情败类
感情败类 2020-12-02 10:33

I\'ve searched stackoverflow and googled four a couple of hours and still not found any solution for my \"trivial\" problem.

If you write unit test for your filtered

相关标签:
1条回答
  • 2020-12-02 11:21

    You need to mock a context for your controller. Try using Moq

    Your arrange would then look like:

    var controller = new UserController();
    var mock = new Mock<ControllerContext>();
    mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
    mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
    controller.ControllerContext = mock.Object;
    

    You should be able to then do your Act & Assert.

    If you haven't already, I would highly recommend looking through NerdDinner as an example MVC site.

    0 讨论(0)
提交回复
热议问题