Let's say I have the following model:
public class A
{
public decimal? Property { get; set; }
}
And I want to test a method, depending on that "Property", passing values as a parameter. I thought this will work, but I'm not surprised it doesn't, since the InlineData attribute accepts an array of objects.
[Theory]
[InlineData(-10.0)]
[InlineData(0)]
[InlineData(null)]
public void Test(decimal? property)
{
var a = new A();
a.Property = property;
// Unit test logic
}
When running the tests, it passes for the null value, but the numeric values throw "ArgumentException" exception:
System.ArgumentException : Object of type 'System.Double' cannot be converted to type 'System.Nullable`1[System.Decimal]'.
My question is: is it possible to use [Theory] & [InlineData] for such cases? Or should I have a separate test for each?
CodePudding user response:
I found this question
The second answer is a workaround that seems to work, change the signature to receive a double?
and then cast it to decimal?
[Theory]
[InlineData(-10.0)]
[InlineData(0)]
[InlineData(null)]
public void Test(double? property)
{
var a = new A();
a.Property = (decimal?) property;
// Unit test logic
}