使用Inlinedata时C#Xunit转换问题

发布于 2025-02-03 03:15:37 字数 661 浏览 2 评论 0原文

假设我有以下模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

亽野灬性zι浪 2025-02-10 03:15:38

我发现这个问题

第二个答案是似乎有效的解决方法,更改签名以接收double?,然后将其施放为十进制?

[Theory]
[InlineData(-10.0)]
[InlineData(0)]
[InlineData(null)]
public void Test(double? property)
{
    var a = new A();
    a.Property = (decimal?) property;
    // Unit test logic
}

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
}
绿萝 2025-02-10 03:15:38

您可以声明这些值是用m将其声明为十进制字面的十进制。

[Theory]
[InlineData(-10.0M)]
[InlineData(0M)]
[InlineData(null)]
public void Test(decimal? property)
{
    var a = new A();
    a.Property = property;
    // Unit test logic
} 

You can declare that the values are decimal with M to declare it as a decimal literal.

[Theory]
[InlineData(-10.0M)]
[InlineData(0M)]
[InlineData(null)]
public void Test(decimal? property)
{
    var a = new A();
    a.Property = property;
    // Unit test logic
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文