【问题标题】:MVC Action attribute testingMVC Action 属性测试
【发布时间】:2013-01-11 10:29:53
【问题描述】:

我有一个具有以下操作的 MVC3 应用程序。

public class FooController : ApplicationController
{
  [My(baz: true)]
  public void Index()
  {
    return view("blah");
  }
}

我可以使用 MVCContrib 的 TestHelper 以这种方式编写一个测试来验证 Index 是否被 MyAttribute 修饰。

[TestFixture]
public class FooControllerTest
{
  [Test]
  public void ShouldHaveMyAttribute()
  {
    var fooController = new FooController();
    fooController.Allows(x => x.Index(), new List<Type>{typeof(MyAttribute)});
  }
}

问题 - 如何更改此测试以测试 MyAttribute 装饰是否包含属性“baz”为真?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 mvccontrib


    【解决方案1】:

    如果您想在单元测试中验证属性,您需要使用反射来检查您的控制器方法,如下所示。

    [TestFixture]
    public class FooController Tests 
    {
        [Test]
        public void Verify_Index_Is_Decorated_With_My_Attribute() {
            var controller = new FooController ();
            var type = controller.GetType();
            var methodInfo = type.GetMethod("Index");
            var attributes = methodInfo.GetCustomAttributes(typeof(MyAttribute), true);
            Assert.IsTrue(attributes.Any(), "MyAttribute found on Index");
            Assert.IsTrue(((MyAttribute)attr[0]).baz);
        }
    }
    

    这可能对你有帮助

    【讨论】:

    • 是的,反射绝对是一种选择,但我一直在寻找比这更简单的东西。只是为了测试参数,我的两个线性测试需要增长。
    • 哦,我知道您现在正在使用 MVCContrib 的测试助手,不确定是否有任何其他选项可以检查您的状况。
    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2019-04-07
    相关资源
    最近更新 更多