Question

I am using this code to setup my mvc app in a [Test] (to be re-factored and moved into [Setup] etc.):

// arrange
var mockSomeService = new Mock<ISomeService>();
mockSomeService.Setup(m => m.IsTrue()).Returns(false);   
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterProviders.Providers.Add(new FilterProvider(mockSomeService.Object));
var controller = new HomeController();

// act
var result = controller.Index() as ViewResult;

for some reason the AuthorizeAttribute defined in FilterProvider is never kicking in but when I test the mvc app manually it works fine. Am I missing something in terms of setup in this integration test?

Was it helpful?

Solution

Filters are invoked as part of the request pipeline so they won't get triggered by a direct invocation of an action method as you've got in your test.

I don't think you're missing out on much there though, because the request pipeline and its invoking of filters has been heavily tested by lots of other people, so you can just write your test directly against the filter object instead.

OTHER TIPS

I have been working on a library to help testing asp.net-mvc application with all there filters, validators, routing and authentication. This example shows how to add a custom filter provider. To use it u need add a nuget package Xania.AspNet.Simulator.

using Xania.AspNet.Simulator;
.....

[Test]
public void CustomFilterProviderTest()
{
    // arrange
    var action = new AccountController().Action(c => c.ChangePassword(null));
    action.FilterProviders.Add(new CustomFilterProvider());

    // act
    var result = action.Execute();

    // assert
    Assert.AreEqual("Your Message", result.ViewBag.Message);
    Assert.IsTrue(result.ModelState.IsValid);
    Assert.IsInstanceOf<ViewResult>(result.ActionResult);
    ...
}

More examples can be found at github https://github.com/ibrahimbensalah/Xania.AspNet.Simulator/tree/master/Xania.AspNet.Simulator.Tests

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top