简体   繁体   English

在ASP.NET MVC集成测试中设置IFilterProvider

[英]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.): 我正在使用以下代码在[测试]中设置我的mvc应用程序(将其重构并移至[设置]等):

// 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. 由于某些原因,FilterProvider中定义的AuthorizeAttribute永远不会生效,但是当我手动测试mvc应用程序时,它可以正常工作。 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. 我一直在开发一个库,以帮助测试带有所有筛选器,验证器,路由和身份验证的asp.net-mvc应用程序。 This example shows how to add a custom filter provider. 本示例说明如何添加自定义过滤器提供程序。 To use it u need add a nuget package Xania.AspNet.Simulator. 要使用它,您需要添加一个nuget包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 更多示例可以在github https://github.com/ibrahimbensalah/Xania.AspNet.Simulator/tree/master/Xania.AspNet.Simulator.Tests中找到

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

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