7

I have simple method which calculates a given calculation from a list. I would like to write some tests for this method.

I am using NUnit. I am using TestCaseSource because i am trying to give a list as parameter. I have the solution from this question. My tests looks like this:

[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"));
        }
    }

I would like to test multiple calculations like with testCases.

TestCases have the Result parameter. How could I add a Result to TestCaseSource so i can test multiple calculations?

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Nightscape
  • 464
  • 6
  • 19

2 Answers2

13

You can use TestCaseData attribute for that. It allows you to encapsulate test data in a separate class and reuse for other tests

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;
}
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
4

Looks like this should work:

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));
}
Renat
  • 7,718
  • 2
  • 20
  • 34
  • 1
    You don't need to also annotate with `[Test]` if you annotate with `[TestCaseSource]`. This should be fine: `[TestCaseSource(nameof(_data))] public void Test(List calculation, string expectedResult) { ... }`. – ANeves Jan 13 '20 at 15:51