c# an attribute argument must be a constant expression

11,175

Solution 1

This does not answer to the title of question, however it solves your specific problem.

You might want to use TestCaseSource, it allows you to pass multiple test case scenarios into the same testing mechanism, and you can use it as complex structures as you like.

    [Test]
    [TestCaseSource("TestCaseSourceData")]
    public void Test(String[] recordNumber, string testName)
    {
        //something..
    }

    public static IEnumerable<TestCaseData> TestCaseSourceData()
    {
        yield return new TestCaseData(new string[] {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"}, "Checking10WOs");
    }

It will figure out that the first parameter is recordNumber and the second is testName

see the screenshot below.

enter image description here

Hope this saves you some time.

Solution 2

The strings are all constant but the array they are in is not. Try this instead:

[Test]
[TestCase("01","02","03","04","05","06","07","08","09","10", TestName="Checking10WOs")]
public void Test(String recordNumber)
{
     //something..
} 

This works because TestCaseAttribute accepts its cases as a params list.

Share:
11,175
GucciProgrammer
Author by

GucciProgrammer

Updated on July 04, 2022

Comments

  • GucciProgrammer
    GucciProgrammer almost 2 years

    Why does my String array below give me an Error, arent they all strings??? "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

    [Test]
    [TestCase(new string[]{"01","02","03","04","05","06","07","08","09","10"},TestName="Checking10WOs")]
    public void Test(String[] recordNumber)
    {
         //something..
    } 
    
  • GucciProgrammer
    GucciProgrammer over 9 years
    Thanks, it solved the error but when I executed the test on Nunit, it gave me the error "the number of params do not match". I was able to solve it using [TestCase(3, new String[]{"01","02","03","04","05","06","07","08","09","10"}, TestName="Checking10WOs")] public void SwitchingLevelsFromWOLevel(int a, String[] recordNumber) I just passed a useless parameter and it worked. not sure why
  • Patrick Quirk
    Patrick Quirk over 9 years
    @GucciProgrammer See my edit, your test's parameter needs to be a single string. Oddly enough it does work, but you'll run one test with an array of strings. I thought you wanted to run that test 10 times with a single string parameter.