Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Result to TestCaseSource

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?

like image 769
Nightscape Avatar asked Dec 31 '22 19:12

Nightscape


2 Answers

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;
}
like image 104
Pavel Anikhouski Avatar answered Jan 10 '23 14:01

Pavel Anikhouski


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));
}
like image 34
Renat Avatar answered Jan 10 '23 13:01

Renat