Passing a string to attribute argument by calling method

前提是你 提交于 2019-12-20 02:15:45

问题


I'm trying to use NUnit and pass in a string argument to the TestCase attribute but I get "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

This is a simplified version but MyStatic is a call that returns a built up RegEx string, so each method in MyStatic that is called appends to a stringbuilder and has an implicit conversion to string.

I want to keep this method because if I create separate unit tests I'd be going against the DRY principle.

  [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]);
  }

回答1:


Try using TestCaseSource for those kind of arguments: http://www.nunit.org/index.php?p=testCaseSource&r=2.5.9

example from the documentation:

 [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 } 
 };

in your case:

 [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" },
 };


来源:https://stackoverflow.com/questions/10687091/passing-a-string-to-attribute-argument-by-calling-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!