Reputation: 1118
Using c#, Nunit 3.
I have test case source, which many of my tests share. Something like:
public static IEnumerable TestCaseSourceMethod()
{
foreach (String str in someMethodHere)
{
//do some stuff
yield return new TestCaseData(newString).SetCategory(testCategory);
}
}
And I use it in Tests like
[Test, TestCaseSource("TestCaseSourceMethod")]
...
Now I have new test method, that should use the same data from TestCaseSourceMethod but needs additional test argument.
I came up with something like:
foreach (TestCaseData tcd in TestCaseSourceMethod())
{
//how to change tcd to include new test case argument, or create new test case data based on tcd
yield return newtcd;
}
I am able to do tcd.Returns("aaa");
in order to change the expected returned value, or tcd.SetCategory("aaaaa");
, but I wasn't able to find a way to change the test case arguments themselves.
Upvotes: 1
Views: 1796
Reputation: 32455
You can always move common logic in own method and re-use it.
Create method which do some stuff and return parameter for the tests
public static string DoSomeStaff(string someValue)
{
// do some stuff
return newString;
}
Then
public static IEnumerable TestCaseSourceMethod()
{
foreach (String str in someMethodHere)
{
var newString = DoSomeStaff(str);
yield return new TestCaseData(newString).SetCategory(testCategory);
}
}
public static IEnumerable SpecialTestCaseSourceMethod()
{
foreach (String str in someMethodHere)
{
var newString = DoSomeStaff(str);
var otherArgument = GetOtherArgument();
yield return new TestCaseData(newString, otherArgument).SetCategory(testCategory);
}
}
Another approach - create extension method, which return new TestCaseData
with extra arguments. Returning new instance of TestCaseData
is important in case when tests executed in parallel.
public static TestCaseData AddArguments(this TestCaseData source, params object[] args)
{
var arguments = source.Arguments.Concat(args).ToArray();
return new TestCaseData(arguments);
}
And use it in method which generate special cases
public static IEnumerable SpecialTestCaseSourceMethod()
{
foreach (var testcase in TestCaseSourceMethod())
{
yield return testcase.AddArguments(otherArgument, extraArgument);
}
}
You can copy category from original test case inside AddArguments
methods.
As mentioned before, it is good to have different instances of test case data, because of possible problems when tests executed in parallel.
Name of method AddArguments
public static TestCaseData AddArguments(this TestCaseData source, params object[] args)
{
var arguments = source.Arguments.Concat(args).ToArray();
var category = source.Properties.Get(PropertyNames.Category).ToString();
return new TestCaseData(arguments).SetCategory(category);
}
Upvotes: 3