I want to pass different test parameters using NUnit Test.
I can pass integer array, no problem, but when I pass string array it does not work.
[TestCase(new[] { "ACCOUNT", "SOCIAL" })]
public void Get_Test_Result(string[] contactTypes)
{
}
Error 3 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type ... \ContactControllerTests.cs 78 13 UnitTests
It works when I use string array as a second argument.
So what is the reason?
[TestCase(0, new[] {"ACCOUNT", "SOCIAL"})]
public void Get_Test_Result(int dummyNumber, string[] contactTypes)
{
}
As k.m says, I believe the compilation error is a result of overload resolution & arrays co-variance, and the suggestion to cast to object did not work for me.
However, specifying the argument name (arg, in the case of TestCaseAttribute) fixes the mix up in overload resolution as you are specifying exactly which overload you want:
[TestCase(arg:new string[]{"somthing", "something2"})]
This compiles and works for me.
I believe this is a case of overload resolution & arrays co-variance issue.
With [TestCase(new string[] { "" })]
compiler decides the best overload for TestCase
constructor is the one taking params object[]
as argument. This is because compiler can assign string[]
to object[]
thanks to arrays co-variance and as a result this is more specific match than string[]
to object
assignment (other constructor).
This doesn't happen with int[]
because co-variance does not apply to arrays of value types so compiler is forced to use object
constructor.
Now, why it decides that new [] { "ACCOUNT", "SOCIAL" }
is not an array creation expression of an attribute parameter type is beyond me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With