将结果添加到 TestCaseSource

Add Result to TestCaseSource

我有一个简单的方法,可以从列表中计算给定的计算。 我想为此方法编写一些测试。

我正在使用 NUnit。我正在使用 TestCaseSource 因为我试图给出一个列表作为参数。我从这个 question 得到了解决方案。 我的测试如下所示:

[TestFixture]
    public class CalcViewModelTests : CalcViewModel
    {
        private static readonly object[] _data =
            {
                new object[] { new List<string> { "3", "+", "3" } },
                new object[] { new List<string> { "5", "+", "10" } }
            };

        [Test, TestCaseSource(nameof(_data))]
        public void Test(List<string> calculation)
        {
            var result = SolveCalculation(calculation);

            Assert.That(result, Is.EqualTo("6"));
        }
    }

我想像使用 testCases 一样测试多个计算。

测试用例有 Result parameter。我怎样才能将结果添加到 TestCaseSource 以便我可以测试多个计算?

看起来应该可行:

private static readonly object[] _data =
    {
        new object[] { new List<string> { "3", "+", "3" }, "6" },
        new object[] { new List<string> { "5", "+", "10" }, "15" }
    };

[Test, TestCaseSource(nameof(_data))]
public void Test(List<string> calculation, string expectedResult)
{
    var result = SolveCalculation(calculation);

    Assert.That(result, Is.EqualTo(expectedResult));
}

您可以为此使用 TestCaseData 属性。它允许您将测试数据封装在一个单独的 class 中并重新用于其他测试

public class MyDataClass
{
    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData("3", "+", "3").Returns("6");
            yield return new TestCaseData("5", "+", "10").Returns("15");
        }
    }  
}

[Test]
[TestCaseSource(typeof(MyDataClass), nameof(MyDataClass.TestCases))]
public string Test(List<string> calculation)
{
      var result = SolveCalculation(calculation);
      return result;
}