rupweb
rupweb

Reputation: 3328

c# nunit TestCaseSource can't provide unique test data for each test run

I am using nunit TestCase and TestCaseSource like here and have the following question about TestCaseSource. When the test code is:

[Test, TestCaseSource("TestData")]
void Test1(string uniqueId){...}

private static IEnumerable<TestCaseData> TestData()
{
    string uniqueId = "myString";         
    yield return new TestCaseData(uniqueId);
}

then the TestCaseSource works and the Test1 runs with the uniqueId variable, but when the test code is:

private static IEnumerable<TestCaseData> TestData()
{
    string uniqueId = Guid.NewGuid().ToString().Substring(0, 8);
    yield return new TestCaseData(uniqueId);
}

then while the TestCaseSource appears to return fine, the Test1 doesn't run. Please comment.

Upvotes: 0

Views: 1132

Answers (2)

Chris
Chris

Reputation: 6072

Using NUnit's random class should solve this problem.

This issue is that the test name is created using the parameter to TestCaseData. In some situations (e.g. if you're using the VS Test Adapter) TestCaseSources are enumerated more than once. If a test of the same name can't be found again - things go wrong. This is why manually setting the name fixes the issue.

If you use the NUnit random class, then the random value is seeded and repeatable (which is probably generally a good idea for any test using random data anyway!)

Try this:

private static IEnumerable<TestCaseData> TestData()
{
    string uniqueId = TestContext.CurrentContext.Random.NextGuid().ToString().Substring(0, 8);
    yield return new TestCaseData(uniqueId);
}

Note that the NextGuid() method is part of NUnit 3.8, which will be released towards the end of the month. For now, you can get a package from the MyGet feed, rather than NuGet: https://www.myget.org/F/nunit/api/v2

Upvotes: 3

rupweb
rupweb

Reputation: 3328

It works if I add a .SetName("myName") as follows:

private static IEnumerable<TestCaseData> TestData()
{
    string uniqueId = Guid.NewGuid().ToString().Substring(0, 8);
    yield return new TestCaseData(uniqueId)
    .SetName("myTest");
}

Upvotes: 0

Related Questions