在DataRowAttribute

时间:2017-05-04 15:23:39

标签: c# unit-testing mstest visual-studio-2017

我已经使用MSTest.TestAdaptor 1.1.17在Visual Studio 2017中运行测试的c#程序集。 我想使用DataTestMethod来运行包含多个数据集的测试。我的问题是,我想在我的DataRows中使用小数值,但不能:

[DataTestMethod]
[DataRow(1m, 2m, 3m)]
[DataRow(1, 2, 3)]
[DataRow(1.0, 2.0, 3.0)]
public void CheckIt(decimal num1, decimal num2, decimal expected)
{
}

当我尝试使用[DataRow(100m, 7m, 7m)]时,它甚至无法编译来源:error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

当我使用[DataRow(100, 7, 7)]时,测试会失败,因为我的测试需要decimal,但会将int32作为值。

当我使用[DataRow(100.0, 7.0, 7.0)]时,测试会失败,因为我的测试需要decimal,但会将double作为值。

为什么我不能在DataRow中使用十进制数?

2 个答案:

答案 0 :(得分:11)

因为小数不是primitive type

解决方案是使用字符串,然后在测试中转换参数。

答案 1 :(得分:1)

这是 C# 的限制,而不仅仅是测试框架的限制。您还可以使用 DynamicData 属性来查询数据的静态属性或方法。你让它输出对象数组的数组。这是每个“数据行”的一项,并且在您希望提供的每个参数的一项中。您也不限于传递原始类型,您可以将任意对象传递给您的参数。这是https://stackoverflow.com/a/47791172的一个很好的例子。

以下是传递小数的示例:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        // static!
        public static IEnumerable<object[]> TestMethod1Data =>
            // one item per data row
            new[] {
                // one item per parameter, you need to specify the object type
                new object[] { 1m, 2m, 3m },
                new object[] { 13.5m, 178.8m, 192.3m }
            };

        [TestMethod]
        // you can also use a method, but it defaults to property
        [DynamicData(nameof(TestMethod1Data))]
        public void TestMethod1(decimal l, decimal r, decimal expected)
        {
            Assert.AreEqual(expected, l  +  r);
        }
    }
}