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?
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;
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With