Reputation: 7073
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)
{
}
Upvotes: 10
Views: 3281
Reputation: 3306
Another way by using TestCaseSource attribute:
[TestCaseSource((typeof(AccountTypes))]
public void Get_Test_Result(string[] contactTypes)
{
}
public class AccountTypes : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new string[] { "ACCOUNT", "SOCIAL" };
}
}
Upvotes: 0
Reputation: 182
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.
Upvotes: 5
Reputation: 31454
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.
Upvotes: 3
Reputation: 16201
Consider doing as follows
[TestCase("ACCOUNT", "SOCIAL")]
public void Test1()
{
}
Not sure if your test would be similar to mine. But I got the expected result with the following test
[TestFixture]
public class TestCaseTest
{
[TestCase("ACCOUNT","SOCIAL")]
public void Get_Test_Result(String a, String b)
{
Console.WriteLine("{0},{1}",a,b);
}
}
And the result
Additionally, if you want some reference to the TestCaseAttribute
Upvotes: 0