简体   繁体   中英

setup of IFilterProvider in asp.net mvc integration test

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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