10
votes

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)
{
}
4
Did you try specify array type explicitly? new string[] { ... }?abatishchev
@abatishchev Yes but it does not work.codebased
I see. Bummer. What version of NUnit do you use?abatishchev

4 Answers

4
votes

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.

3
votes

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.

0
votes

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

enter image description here

Additionally, if you want some reference to the TestCaseAttribute

0
votes

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" };
    }
}