1

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?

Themelis
  • 4,048
  • 2
  • 21
  • 45
  • Is that the exact text of the error? You should post error messages verbatim when possible. – Wyck May 07 '20 at 12:56
  • 1
    You can achieve this using ClassData instead of InlineData (a nice example can be found here https://andrewlock.net/creating-parameterised-tests-in-xunit-with-inlinedata-classdata-and-memberdata/) or with MemberData – Claudiu A May 07 '20 at 12:56
  • Allright I'll post the exact text of the error @Wyck – Themelis May 07 '20 at 12:58

1 Answers1

5

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)   
{    
}
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66