Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 2.2: xUnit Theory Inlinedata not working with enum values

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.

like image 556
IngoB Avatar asked May 25 '19 16:05

IngoB


2 Answers

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.

like image 147
Aage Avatar answered Nov 15 '22 08:11

Aage


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

like image 3
Nkosi Avatar answered Nov 15 '22 09:11

Nkosi