通过调用方法将字符串传递给属性参数

本文关键字:属性 参数 字符串 调用 方法 | 更新日期: 2023-09-27 18:34:45

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

这是一个简化版本,但 MyStatic 是一个返回已建立的正则表达式字符串的调用,因此 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]);
  }

通过调用方法将字符串传递给属性参数

尝试使用 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" },
 };