NUnit cannot recognise a TestCase when it contains an array

守給你的承諾、 提交于 2019-12-04 15:13:46

问题


This is quite simple but annoying behaviour I am running into with NUnit:

I have some tests like this:

[Test]
[TestCase( 1, 2, "hello" )]
[TestCase( 3, 5, "goodbye" )]
public void MyClass_MyMethod( int a, int b, string c )
{
    Assert.IsTrue( a < b );
}

This works fine and in the ReSharper NUnit pane I can see each TestCase getting its own response in the result.

I have a second TestCase that looks like this:

[Test]
[TestCase( 1, 2, new long[] { 100, 200 })]
[TestCase( 5, 3, new long[] { 300, 500 })]
public void MyClass_MyOtherMethod( long a, long b, long[] bunchOfNumbers )
{
   Assert.IsTrue( a < b );
}

When I run it I see this:

One or more child tests had errors Exception doesn't have a stacktrace

public void MyClass_MyOtherMethod(5,3,System.Int64[]) failed

The difference being that with my other tests it draws out each TestCase as a separate checkbox on the test list, whereas this one does not get shown and I have no detail until I run it in a debugger as to what went wrong and where. I am a little concerned about how this test will behave on the build machine. Does anyone have any idea what is going on and why?


回答1:


Following on from this bug at JetBrains it looks as though the solution here is to use the TestName attribute on your different cases:

[Test]
[TestCase( 1, 2, new long[] { 100, 200 }, TestName="Test 1" )]
[TestCase( 5, 3, new long[] { 300, 500 }, TestName="Test 2" )]
public void MyClass_MyOtherMethod( long a, long b, long[] bunchOfNumbers )
{
   Assert.IsTrue( a < b );
}

Everything now shows correctly in ReSharper if one of my tests fails.




回答2:


An alternative is to use a string for the array:

[TestCase( 1, 2, "100, 200")]
[TestCase( 5, 3, "300, 500")]
public void MyClass_MyOtherMethod(long a, long b, string bunchOfNumbersString)
{
    var bunchOfNumbers= bunchOfNumbersString.Split(',')
                                            .Select(long.Parse)
                                            .ToArray();
   ...
}

The upside with this approach is that it will render nicly in the testrunner.

Side note: The [Test] is not needed when using [TestCase] or at least I don't see that it solves a problem.




回答3:


For an array that contains strings, use an object array with the TestCase attributes along with params:

[Test]
[TestCase(new object[] {"foo", "bar", "baz"})]
[TestCase(new object[] {"300", "500", "700"})]    
public void MyClass_SomeOtherMethod(params string[] bunchOfStrings)
{
    // assert something...
}



回答4:


This works in VS 2017 with NUnit 3.11.0

[TestCase(new long[] {5, 6, 942135153})]
public void DummyTest(long[] values)
{
    Assert.That(values != null);
}


来源:https://stackoverflow.com/questions/17925916/nunit-cannot-recognise-a-testcase-when-it-contains-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!