c# - 如何将值传递给接受可为 null 的小数的 xUnit 测试?

标签 c# xunit

我的一个单元测试有这个签名:

public void FooWithFilter(string fooId, decimal? amount)

当我用 null 测试它时,它有效:

[InlineData("123", null)]

但如果我使用实际值,例如:

[InlineData("123", 610)]

我得到一个错误:

System.ArgumentException Object of type 'System.Int32' cannot be 
converted to type 'System.Nullable`1[System.Decimal]'.

我尝试使用 610M 作为属性值,但不允许将其用作属性值:

An attribute argument must be a constant expression, type of expression
or array creation expression of an attribute parameter type.

有没有办法在这里使用可为空的小数?

最佳答案

如评论中所述,您不能使用 decimal这里是因为decimal不是属性参数值中允许的类型之一。

但是,xUnit 提供了一种更灵活的方法来将参数值传递给测试方法,使用 ClassData :

[Theory]
[ClassData(typeof(FooDataGenerator))]
public void FooWithFilter(string fooId, decimal? amount)

要使用它,您只需定义一个扩展 IEnumerable<object[]> 的类并产生你想要的输入值:

public class FooDataGenerator : IEnumerable<object[]>
{
    private readonly List<object[]> _data = new List<object[]>
    {
        new object[] {"123", null},
        new object[] {"123", 610M}
    };

    public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

关于将值传递给 xUnit 测试的各种方法的一些进一步引用:
Creating Parameterised tests in xUnit
xUnit Theory: Working With InlineData, MemberData, ClassData

关于c# - 如何将值传递给接受可为 null 的小数的 xUnit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51544883/

相关文章:

c# - Monotouch 和 WCF : difference of SVCUTIL. EXE 和 SLSVCUTIL.EXE 以及如何避免不受支持的通用 ChannelFactory?

c# - 将 WindowsAzure.ServiceBus 迁移到 Azure.Messaging.ServiceBus

visual-studio-2015 - 测试发现期间出现 Visual Studio dotnet 核心套接字错误

c# - JetBrains.ReSharper.TaskRunnerFramework.dll 中的“System.IO.EndOfStreamException”

C#- "Object reference not set to an instance of an object"

C# 堆栈推送调用问题

c# - 如何在测试时启动两个相互调用的项目?

当初始化程序具有依赖性时,F# XUnit 测试死锁

c# - 在 XUnit 中用理论测试异常

c# - 是否可以从 Sqlite 查询返回动态对象或数据集?