简体   繁体   English

MVC MSpec测试未达到[Authorize]属性

[英]MVC MSpec test not hitting [Authorize] attribute

I have an MSpec test to check whether my forms auth is correctly redirecting an unauthorised request, however the test call to the protected action just goes straight to it without getting caught by the authorisation. 我有一个MSpec测试来检查我的表单身份验证是否正确重定向了未授权的请求,但是对受保护操作的测试调用直接进入了该操作,而没有被授权捕获。 From what I've read people usually need to fake authentication to test actions behing the [Authorize] tag, so I don't understand how it's just going straight to the protected action method. 从我读到的内容来看,人们通常需要伪造身份验证以测试[Authorize]标签中的行为,因此我不知道它是如何直接用于受保护的行为方法的。

If anyone could help it would be much appreciated, this is my first attempt at using MSpec and it looks like it should be really useful, I just can't get it to work! 如果有人可以帮助,将不胜感激,这是我第一次使用MSpec,它看起来应该真的很有用,但我无法使其正常工作!

Controller: 控制器:

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View("Index", null);
    }
}

Test: 测试:

[Subject("Login and Authentication")]
public class when_protected_page_invoked
{
    private static HomeController homeController;
    private static SecurityController securityController;
    private static ActionResult result;

    private Establish context = () =>
    {
        homeController = new HomeController();
        securityController = new SecurityController(new SecurityService(new NHibernateRepository<User>(), new NHibernateRepository<Session>()));
    };

    private Because of = () => result = homeController.Index();

    private It should_redirect_to_securityController = () =>
        {
            result.ShouldBeARedirectToRoute().And().ControllerName().ShouldEqual("Security");
        };
}

When I run the test at the moment it fails with an exception that a ViewResult is being returned, and if I debug it's just returning the Home.Index() result. 当我运行测试时,它失败了,但返回了ViewResult,但如果我调试它,则只是返回Home.Index()结果。

That's normal. 那很正常 Action filters are not executed in this case. 在这种情况下,不执行动作过滤器。 All you do is to call the action method in your unit test. 您要做的就是在单元测试中调用action方法。 The proper way to unit test this is to verify that this controller is decorated with the Authorize attribute: 对此进行单元测试的正确方法是验证此控制器是否装饰有Authorize属性:

Assert.IsTrue(typeof(HomeController).GetCustomAttributes(typeof(AuthorizeAttribute), true).Any());

The fact that when a controller is decorated with the Authorize attribute will redirect to the proper login page if the user is not authneticated is not something that you should unit test. 如果未对用户进行身份验证,则用Authorize属性修饰控制器时,将重定向到正确的登录页面,这一事实不应该进行单元测试。 That's part of the ASP.NET MVC framework which Microsoft (hopefully) have already extensively unit tested. 那是ASP.NET MVC框架的一部分,微软(希望如此)已经对该框架进行了广泛的单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM