'C#: Parametrize an NUnit test with several number types

I want to test the simple + operator with several types of numbers: int, float, double ...

To do this, I want to use Nunit TestCaseSource attribute. So far, the only way I found to do it is the following:

public class TestAdditionExample
{
    
    public static IEnumerable<TestCaseData> GetTestsCasesInts()
    {
        yield return new TestCaseData(1, 2, 3);
        yield return new TestCaseData(1, -2, -1);
    }
    
    public static IEnumerable<TestCaseData> GetTestsCasesFloats()
    {
        yield return new TestCaseData(1.03f, 2.1f, 3.13f);
        yield return new TestCaseData(1.03f, -2.1f, -1.07f);
    }

    public static IEnumerable<TestCaseData> GetTestsCasesDoubles()
    {
        yield return new TestCaseData(1.03, 2.1, 3.13);
        yield return new TestCaseData(1.03, -2.1, -1.07);
    }
    
    [Test, TestCaseSource(nameof(GetTestsCasesInts))]
    public void TestAdditionOfInts(int a, int b, int c)
    {
        Assert.AreEqual(a+b, c);
    }
    
    [Test, TestCaseSource(nameof(GetTestsCasesFloats))]
    public void TestAdditionOfFloats(float a, float b, float c)
    {
        Assert.AreEqual(a+b, c);
    }
    
    [Test, TestCaseSource(nameof(GetTestsCasesDoubles))]
    public void TestAdditionOfDoubles(double a, double b, double c)
    {
        Assert.AreEqual(a+b, c);
    }
}

As you can see, because the type of the argument must be specified as a test function parameter, I have to create three identical tests functions (except the argument type), and three set of TestCaseSource.

Would you think of a better, more elegant solution, to do this ?



Solution 1:[1]

You could make this work with dynamics:

public class TestAdditionExample
{
    
    public static IEnumerable<dynamic> GetTestsCases()
    {
        yield return new TestCaseData(1, 2, 3);
        yield return new TestCaseData(1, -2, -1);
        yield return new TestCaseData(1.03f, 2.1f, 3.13f);
        yield return new TestCaseData(1.03f, -2.1f, -1.07f);
        yield return new TestCaseData(1.03, 2.1, 3.13);
        yield return new TestCaseData(1.03, -2.1, -1.07);
    }
    
    [Test, TestCaseSource(nameof(GetTestsCases))]
    public void TestAddition(dynamic a, dynamic b, dynamic c) 
    {
        Assert.AreEqual(a+b, c);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sean Manton