Search code examples
c#unit-testingnunitassertionsnunit-3.0

Which collection assertion strategy is used with TestCaseSource collection return values


Using nUnit 3.4.1.

When using TestCaseSource to new up a list of TestCaseData items:

new TestCaseData(new [] {"value1", "value2"}).Returns(new [] {"value2", "value1"})

in my unit test, when returning an array that looks like the input data:

new [] {"value1", "value2"}

for the Returns value shown above, I get a failed test, because I'm assuming nUnit is using CollectionAssert.AreEqual, which implies the same order.

Tried using an extra parameter in the TestCaseData initialization and a CollectionAssert.AreEquivalent instead, and it worked

Can I customize that behavior?


Solution

  • The behaviour is not configurable. The fluent Returns method is treated the same as ExpectedResult. NUnit only checks for equality. The NUnit code that handles this is fairly straight forward,

    if (testMethod.HasExpectedResult)
        NUnit.Framework.Assert.AreEqual(testMethod.ExpectedResult, result);
    

    The workaround to pass in the expected value as a second parameter and use the CollectionAssert.AreEquivalent is the correct one. NUnit will not be changing the semantics of ExpectedResult to allow you to use arbitrary asserts. You are likely seeing AreEqual and AreEquivalent as very close in semantic meaning, but they are very different internally.