【问题标题】:Passing a string to attribute argument by calling method通过调用方法将字符串传递给属性参数
【发布时间】:2012-05-21 14:22:42
【问题描述】:

我正在尝试使用 NUnit 并将字符串参数传递给 TestCase 属性,但我得到 “属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式” em>

这是一个简化的版本,但 MyStatic 是一个返回构建的 RegEx 字符串的调用,因此 MyStatic 中被调用的每个方法都附加到一个字符串构建器并隐式转换为字符串。

我想保留这种方法,因为如果我创建单独的单元测试,我将违反 DRY 原则。

  [TestCase("","/123",MyStatic.DoThis().And().GetString("ABC"), "id","123")]
  public void MyMehthod(string Root, string Path, string Route, string Param, string Expected)
  {
    var result = SetupRouteResponse(Root, Path, Route, "MatchIt");

    Assert.AreEqual(Expected, (string)result.Context.Parameters[Param]);
  }

【问题讨论】:

    标签: c# .net nunit


    【解决方案1】:

    尝试对此类参数使用 TestCaseSource:http://www.nunit.org/index.php?p=testCaseSource&r=2.5.9

    文档中的示例:

     [Test, TestCaseSource("DivideCases")]
     public void DivideTest(int n, int d, int q)
     {
        Assert.AreEqual( q, n / d );
     }
    
     static object[] DivideCases =
     {
        new object[] { 12, 3, 4 },
        new object[] { 12, 2, 6 },
        new object[] { 12, 4, 3 } 
     };
    

    在你的情况下:

     [Test, TestCaseSource("MyCaseSource")]
     public void MyMehthod(string Root, string Path, string Route, string Param, string Expected)
     {
       var result = SetupRouteResponse(Root, Path, Route, "MatchIt");
    
       Assert.AreEqual(Expected, (string)result.Context.Parameters[Param]);
     }
    
     static object[] MyCaseSource=
     {
        new object[] { "","/123",MyStatic.DoThis().And().GetString("ABC"), "id","123" },
     };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      相关资源
      最近更新 更多