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

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like