Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to pass string array

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)
{
}
like image 420
codebased Avatar asked Apr 02 '15 00:04

codebased


Video Answer


2 Answers

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.

like image 107
Julian Hanssen Avatar answered Oct 17 '22 17:10

Julian Hanssen


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.

like image 42
k.m Avatar answered Oct 17 '22 19:10

k.m