3

BaseControllerTest.PrepareController 足以用于控制器属性设置,例如 PropertyBag 和 Context

[TestClass]
public ProjectsControllerTest : BaseControllerTest
{
 [TestMethod]
 public void List()
 {
  // Setup
  var controller = new ProjectsController();
  PrepareController(controller);
  controller.List();

  // Asserts ...
  Assert.IsInstanceOfType(typeof(IEnumerable<Project>),controller.PropertyBag["Projects"]);
 }
}

但是现在要运行整个管道进行集成测试,包括在动作属性中声明的过滤器?

编辑:我对视图渲染不感兴趣,只对控制器逻辑和声明性过滤器感兴趣。

我喜欢将大量视图设置逻辑移动到操作过滤器中的想法,我不确定我是否需要额外级别的集成测试,还是使用 Selenium 做得更好?

4

1 回答 1

2

您可以获取过滤器并运行它们。

所以,假设actionis Action<YourController>,并且controller是被测控制器的一个实例,

var filtersAttributes = GetFiltersFor(controller); // say by reflecting over its attributes
var filters = filtersAttributes
    .OrderBy(attr => attr.ExecutionOrder)
    .Select(attr => new { Attribute = attr, Instance = 
        (IFilter)Container.Resolve(attr.FilterType) }); // assuming you use IoC, otherwise simply new the filter type with Activator.CreateInstance or something

Action<ExecuteWhen> runFilters = when =>
{ 
    // TODO: support IFilterAttributeAware filters
    foreach (var filter in filters) 
         if ((filter.Attribute.When & when) != 0) 
             filter.Instance.Perform(when, Context, controller, controllerContext);
};

// Perform the controller action, including the before- and after-filters
runFilters(ExecuteWhen.BeforeAction);
action(controller);
runFilters(ExecuteWhen.AfterAction);

让视图引擎发挥作用更棘手(尽管可能),但我认为测试生成的视图以及控制器逻辑涉及太多的移动并导致不合理的维护工作

于 2010-03-10T05:24:28.177 回答