Search code examples
c#unit-testingxunit

Is it possible to add inline C# objects to a theory in xUnit?


I have some custom C# objects which I want to pass as InlineData arguments in xUnit's Theory.

I tried the answer in this question without any success since my objects are not strings and therefore cannot be created as compile time constants (An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type).

Here is what I tried,

private static readonly Card sevenOfHearts = Card.SevenOfHearts;
private static readonly Card sevenOfSpades = Card.SevenOfSpades;
private static readonly Card sevenOfDiamonds = Card.SevenOfDiamonds;
private static readonly Card sevenOfClubs = Card.SevenOfClubs;

[Theory]
[InlineData(sevenOfHearts)]
[InlineData(sevenOfSpades)]
[InlineData(sevenOfDiamonds)]
[InlineData(sevenOfClubs)]
void Test(
  Card card)
{
  //...
}

but I am getting complains that those objects are not compile time constants.

Is there any alternative to this?


Solution

  • You can use MemberData attribute for that. It should return IEnumerable<object[]>, where every item represents a set of parameters for your test method (in your case only one Card parameter, so only one item)

    public static IEnumerable<object[]> Cards
    {
        get
        {
            yield return new object[] { Card.SevenOfHearts };
            yield return new object[] { Card.SevenOfSpades };
            yield return new object[] { Card.SevenOfDiamonds };
            yield return new object[] { Card.SevenOfClubs };
        }
    }
    
    [Theory]
    [MemberData(nameof(Cards))]
    void Test(Card card)   
    {    
    }