2023/11/05 - Coenraad Stijne
Note: A follow up post describes how to reimplement NUnit's
[ValuesAttribute]
in MSTest
and xUnit
.
See .NET Unit Test Framework Comparison - Combinatorial Parameters.
NUnit
is the only library that supportEnum
iteration natively.- For
MSTest
andxUnit
, we can create our own custom attributes.
Framework | Version |
---|---|
MSTest | 3.1.1 |
NUnit | 4.5.0 |
xUnit | 2.6.1 |
[AttributeUsage(AttributeTargets.Method)]
public class EnumDataAttribute<T> : Attribute, ITestDataSource where T : struct, Enum
{
public IEnumerable<object?[]> GetData(MethodInfo testMethod) => Enum.GetValues<T>().Select(e => new object[] { e });
public string? GetDisplayName(MethodInfo methodInfo, object?[]? data)
{
return $"{methodInfo.Name}({data![0]})";
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
[EnumData<Season>]
public void EnumIterationTest(Season season) => Console.WriteLine(season);
}
public class Tests
{
[Test]
public void EnumIterationTest([Values] Season season) => Console.WriteLine(season);
}
[AttributeUsage(AttributeTargets.Method)]
public class EnumDataAttribute<T> : DataAttribute where T : struct, Enum
{
public override IEnumerable<object[]> GetData(MethodInfo testMethod) => Enum.GetValues<T>().Select(e => new object[] { e });
}
public class UnitTest1
{
[Theory]
[EnumData<Season>]
public void EnumIterationTest(Season season) => Console.WriteLine(season);
}