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?
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);
}
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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With