11

I have the following test:

[ExpectedException(typeof(ParametersParseException))]
[TestCase("param1")]
[TestCase("param1", "param2")]
[TestCase("param1", "param2", "param3", "optParam4", "optParam5", "some extra parameter")]
public void Parse_InvalidParametersNumber_ThrowsException(params string[] args)
{
    new ParametersParser(args).Parse();
}

The first TestCase (obviously) fails with the following error:

System.ArgumentException : Object of type 'System.String' 
cannot be converted to type 'System.String[]'.

I tried to replace the TestCase definition with this one:

[TestCase(new[] { param1 })]

but now I get the following compilation error:

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

My solution for now is moving the 'one parameter' case to a different test method.

Still, is there a way to get this test to run the same way as the others?

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137

3 Answers3

9

One way could be to use TestCaseSource, and have a method that returns each parameter set, instead of using TestCase.

AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
3

Based on this answer in response to the question 'NUnit cannot recognize a TestCase when it contains an array', the compilation error stems from a bug, and can be overcome using the syntax for named test cases, as such:

[ExpectedException(typeof(ParametersParseException))]
[TestCase(new[] { "param1"}, TestName="SingleParam")]
[TestCase(new[] { "param1", "param2"}, TestName="TwoParams")]
[TestCase(new[] { "param1", "param2", "param3", "optParam4", "optParam5"}, "some extra parameter", TestName="SeveralParams")]
public void Parse_InvalidParametersNumber_ThrowsException(params string[] args)
{
    new ParametersParser(args).Parse();
}
Community
  • 1
  • 1
GoetzOnline
  • 417
  • 8
  • 22
  • You link to a resharper issue, while the problem seems to be in nunit ... in any case, seems like resharper solved the problem – Noctis Oct 03 '14 at 05:35
  • 1
    Doing this with `new[] { ... }` where the array is of strings gives the error CS0182 as referenced by the OP above. Integer types seem to work properly. – Brandon Feb 23 '15 at 18:21
0

Although I don't recommend this approach,

yet here is one more way to pass a single argument to a params array by using a dummy object parameter before the params parameter.

See the example below:

[ExpectedException(typeof(ParametersParseException))]
[TestCase(null, "param1")]
[TestCase(null, "param1", "param2")]
[TestCase(null, "param1", "param2", "param3", "optParam4", "optParam5", "some extra parameter")]
public void Parse_InvalidParametersNumber_ThrowsException(object _, params string[] args)
{
    new ParametersParser(args).Parse();
}

PS A better way to accomplish that would be using the TestCaseSource attribute.

AlexMelw
  • 2,406
  • 26
  • 35