使用Inlinedata时C#Xunit转换问题
假设我有以下模型:
public class A
{
public decimal? Property { get; set; }
}
我想测试一种方法,具体取决于“ 属性”,将值作为参数传递。我认为这会起作用,但我并不感到惊讶,因为Inlinedata属性接受了一系列对象。
[Theory]
[InlineData(-10.0)]
[InlineData(0)]
[InlineData(null)]
public void Test(decimal? property)
{
var a = new A();
a.Property = property;
// Unit test logic
}
运行测试时,它会传递为空值,但是数字值抛出“ grigent exception ”异常:
system.argumentException:类型'system.double'的对象不能为 转换为type'system.nullable`1 [system.decimal]'。
我的问题是:可以使用[理论]& [inlinedata]在这种情况下?还是我应该为每个测试单独测试?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现这个问题
第二个答案是似乎有效的解决方法,更改签名以接收
double?
,然后将其施放为十进制?
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 todecimal?
您可以声明这些值是用
m
将其声明为十进制字面的十进制。You can declare that the values are decimal with
M
to declare it as a decimal literal.