Search code examples
c#decimalxunit.net

Having an actual decimal value as parameter for an attribute (example xUnit.net's [InlineData]


I'm trying to do unit testing with xUnit.net. I want a 'Theory' test with '[InlineData]' which includes 'decimals':

[Theory]
[InlineData(37.60M)]
public void MyDecimalTest(decimal number)
{
    Assert.Equal(number, 37.60M);
}

This is not possible because you cannot create a decimal as a constant.

Question:
Is there a workaround for this?


Solution

  • You should be able use the String value in the Attribute and set the Parameter type to Decimal, it get's converted automatically by the Test Framework as far as I can tell.

    [Theory]
    [InlineData("37.60")]
    public void MyDecimalTest(Decimal number)
    {
        Assert.Equal(number, 37.60M);
    }
    

    If this doesn't work then you can manually convert it by passing in a String parameter.

    [Theory]
    [InlineData("37.60")]
    public void MyDecimalTest(String number)
    {
        var d = Convert.ToDecimal(number);
        Assert.Equal(d, 37.60M);
    }