Just some example code here, but I have lists of strings that I want to test my functions against. The part that I don’t like is that NUnit stops in each test when the first Assert fails. I’d like to test each value and report each failure, rather than just the first one. I don’t want to have to write a new [Test] function for each string though.
Is there a way to do this?
using NUnit.Framework;
using System.Collections.Generic;
namespace Examples
{
[TestFixture]
public class ExampleTests
{
private List<string> validStrings = new List<string> { "Valid1", "valid2", "valid3", "Valid4" };
private List<string> invalidStrings = new List<string> { "Invalid1", "invalid2", "invalid3", "" };
[Test]
public void TestValidStrings()
{
foreach (var item in validStrings)
{
Assert.IsTrue(item.Contains("valid"), item);
}
}
[Test]
public void TestInvalidStrings()
{
foreach (var item in invalidStrings)
{
Assert.IsFalse(item.Contains("invalid"), item);
}
}
}
}
Use the
[TestCaseSource]attribute to specify values to pass into your (now parameterized) test method.We use this a lot in Noda Time to test a lot of cases with different cultures and strings.
Here’s your example, converted to use it:
Note that another option is to use
[TestCase]which means you don’t need separate variables for your test data.