Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
Tim Pohlmann Avatar asked Jun 16 '16 08:06

Tim Pohlmann


3 Answers

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);
}
like image 65
DaveShaw Avatar answered Nov 14 '22 08:11

DaveShaw


Instead of InlineData, use MemberData as shown here. This gives you much greater flexibility in setting up multiple tests and allows the use of decimals or any other non-constant type.

public class CalculatorTests  
{

    public static IEnumerable<object[]> Data =>
        new List<object[]>
        {
            new object[] { 1.2M, 2.1M, 3.3M },
            new object[] { -4.000M, -6.123M, -10.123M }
        };

    [Theory]
    [MemberData(nameof(Data))]
    public void CanAddTheoryMemberDataProperty(decimal value1, decimal value2, decimal expected)
    {
        var calculator = new Calculator();

        var result = calculator.Add(value1, value2);

        Assert.Equal(expected, result);
    }
}
like image 36
StillLearnin Avatar answered Nov 14 '22 09:11

StillLearnin


The NUnit solution (Google landed me here) The accepted answers gave me some ideas so after some research came up with with help from NUnit Sequential Attribute with arrays in Values. The nameof expression is a c# 7 expression

[TestFixture]
public class CalculatorTests
{

    public static IEnumerable<object[]> Data =>
        new List<object[]>
        {
            new object[] { 1.2M, 2.1M, 3.3M },
            new object[] { -4.000M, -6.123M, -10.123M }
        };

    [Test]
    [TestCaseSource(nameof(Data))]
    public void CanAddTheoryMemberDataProperty(decimal value1, decimal value2, decimal expected)
    {
        var calculator = new Calculator();

        var result = calculator.Add(value1, value2);

        Assert.AreEqual(expected, result);
    }
}
like image 39
PBo Avatar answered Nov 14 '22 08:11

PBo