Does anybody know how to use xUnit with "Theory" and "InlineData" with enum
values? This here is leading to the tests not being recognized as tests and not run:
[Theory]
[InlineData("12h", 12, PeriodUnit.Hour)]
[InlineData("3d", 3, PeriodUnit.Day)]
[InlineData("1m", 1, PeriodUnit.Month)]
public void ShouldParsePeriod(string periodString, int value, PeriodUnit periodUnit)
{
var period = Period.Parse(periodString);
period.Value.Should().Be(value);
period.PeriodUnit.Should().Be(periodUnit);
}
The tests work and run if I use the int values of the enum instead of the enum values.
You don't need [MemberData]
, enum
values should work right out of the box. As per the documentation enums
are constants:
An enum type is a distinct value type (Value types) that declares a set of named constants.
Code example below works for me (a .net core 3.1
xUnit Test Project template):
public class UnitTest1
{
public enum Foo { Bar, Baz, Qux }
[Theory]
[InlineData(Foo.Bar, Foo.Baz)]
public void Test1(Foo left, Foo right)
{
Assert.NotEqual(left, right);
}
}
Something else must be giving you troubles.
Attributes for [InlineData]
need constant expressions, e.g int, bool, string etc.
Use [MemberData]
instead if the inline is not recognizing the enum as a constant.
[Theory]
[MemberData(nameof(PeriodData))]
public void ShouldParsePeriod(string periodString, int value, PeriodUnit periodUnit) {
var period = Period.Parse(periodString);
period.Value.Should().Be(value);
period.PeriodUnit.Should().Be(periodUnit);
}
public static IEnumerable<object[]> PeriodData() {
yield return new object[] { "12h", 12, PeriodUnit.Hour };
yield return new object[] { "3d", 3, PeriodUnit.Day };
yield return new object[] { "1m", 1, PeriodUnit.Month };
}
Reference xUnit Theory: Working With InlineData, MemberData, ClassData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With