Search code examples
xunitxunit2

Can XUnit handle tests handle class and decimal parameters in the same method?


I have a test method with the following signature:

public void TheBigTest(MyClass data, decimal result)
{

And I'd like to run this in XUnit 2.1. I've got my CalculationData class all set up and that works if I remove the second parameter. But when I try to pass in the expected result as a second parameter by doing:

[Theory, ClassData(typeof(CalculationData)), InlineData(8893)]

It doesn't work. The test fails with a:

The test method expected 2 parameter values, but 1 parameter value was provided.

Any ideas?


Solution

  • The class specified in the ClassData attribute needs to be an enumerable class that returns all of the parameters for the test method, not just the first one.

    So, in your example, you would need something like:

    public class CalculationData : IEnumerable<object[]>
    {
        IEnumerable<object[]> parameters = new List<object[]>()
        {
            new object[] { new MyClass(), 8893.0m },
            new object[] { new MyClass(), 1234.0m },
            // ... other data...
        };
    
        public IEnumerator<object[]> GetEnumerator()
        {
            return parameters.GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

    You can then add parameters to your MyClass class to enhance your test data.