1

I have a test-method as follows:

[TestCase(new string[] { "1", "2", "5" }, Result = true)]
bool AllocateIDsTest1(IEnumerable<string> expected)
{
    var target = ...
    var actual = target.AllocateIDs(expected);

    return actual.SequenceEqual(expected);
}

However I get a compiler-error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

Probably the compiler can´t distinguish between the following constructors:

TestCase(params object[] args, Named Parameters);

and

TestCase(object ob1, Named Paramaters);

because new string[] { "1", "2", "5" } can be resolved to both params object[] and object.

From this post I know that a string-array should be possible to pass as compile-constants.

How can I provide an array of strings to a TestCase?

Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

1 Answers1

4

I found a solution using the params-approach:

[TestCase("1", "2", "5", Result = true)]
public bool AllocateIDsTest1(params string[] expected)
{
    var target = ...
    var actual = target.AllocateIDs(expected);

    return actual.SequenceEqual(expected);
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Excellent workaround. Another option is to use TestCaseSource, see the docs. – Rob Prouse Jul 11 '16 at 11:27
  • Not even a workaround. :-) It's how TestCase is supposed to be used. The compiler error is not because you passed in an array - that's expressly allowed on attributes. It's because you are asking the attribute constructor to dynamically create the array using new. C# doesn't allow that. – Charlie Jul 11 '16 at 15:09
  • @Charlie So how exactly should assigning an array to an attribute work, when you say "that´s expressly allowed on attributes"? Via a `static` field? – MakePeaceGreatAgain Jul 12 '16 at 06:59