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. 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.

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!

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.

有帮助吗?

解决方案

That's normal. Action filters are not executed in this case. All you do is to call the action method in your unit test. The proper way to unit test this is to verify that this controller is decorated with the Authorize attribute:

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. That's part of the ASP.NET MVC framework which Microsoft (hopefully) have already extensively unit tested.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top