How to populate xUnit [Theory] and [InlineData] with values from a method

Publish date: 2024-03-24

Is there a way to input data into [InlineData] values for xUnit tests? I can't seem to do so as it requires constants.

2

1 Answer

For calling Methods as data you have to use [MemberData] rather than [InlineData]. In MemberData you can specify a function via nameof, which returns the expected parameters as result.

 public static IEnumerable<object[]> GetNumbers() { yield return new object[] { 5, 1, 3, 9 }; yield return new object[] { 7, 1, 5, 3 }; } [Theory] [MemberData(nameof(GetNumbers))] public void AllNumbers_AreOdd_WithMemberData(int a, int b, int c, int d) { Assert.True(IsOddNumber(a)); Assert.True(IsOddNumber(b)); Assert.True(IsOddNumber(c)); Assert.True(IsOddNumber(d)); } 

I am not sure but if I remeber correctly, the function you call, needs to return IEnumerable<object[]>, which XUnit will sort out into the parameters of the test, and you have to use yield return if you want multiple datasets to be used.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobXFtZ2yDeIGOoaawZaSkerG7z66jmqyVYsW2usitZK2glaS%2FunnAp5tmoZ6htq%2Bxw5qrmmWnnsGpedWao66do2Kzs7vMZphmpZWptbCw