C# 如何更改TestCaseData Nunit的测试用例参数
使用c#,Nunit 3 我有很多测试共享的测试用例源。 比如:C# 如何更改TestCaseData Nunit的测试用例参数,c#,nunit,C#,Nunit,使用c#,Nunit 3 我有很多测试共享的测试用例源。 比如: public static IEnumerable TestCaseSourceMethod() { foreach (String str in someMethodHere) { //do some stuff yield return new TestCaseData(newString).SetCategory(testCategory); } } foreach
public static IEnumerable TestCaseSourceMethod()
{
foreach (String str in someMethodHere)
{
//do some stuff
yield return new TestCaseData(newString).SetCategory(testCategory);
}
}
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;
}
我在测试中使用它,比如
[Test, TestCaseSource("TestCaseSourceMethod")]
...
现在我有了新的测试方法,它应该使用来自TestCaseSourceMethod的相同数据,但需要额外的测试参数
我想出了这样的想法:
public static IEnumerable TestCaseSourceMethod()
{
foreach (String str in someMethodHere)
{
//do some stuff
yield return new TestCaseData(newString).SetCategory(testCategory);
}
}
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;
}
我能做
tcd.Returns(“aaa”)
以更改预期的返回值,或tcd.SetCategory(“aaaaa”)代码>,但我无法找到更改测试用例参数本身的方法。您始终可以在自己的方法中移动公共逻辑并重新使用它。
创建方法,该方法执行一些操作并为测试返回参数
public static string DoSomeStaff(string someValue)
{
// do some stuff
return newString;
}
然后
另一种方法是创建扩展方法,它返回带有额外参数的新的TestCaseData
。在并行执行测试的情况下,返回TestCaseData
的新实例非常重要
public static TestCaseData AddArguments(this TestCaseData source, params object[] args)
{
var arguments = source.Arguments.Concat(args).ToArray();
return new TestCaseData(arguments);
}
并在生成特殊情况的方法中使用它
public static IEnumerable SpecialTestCaseSourceMethod()
{
foreach (var testcase in TestCaseSourceMethod())
{
yield return testcase.AddArguments(otherArgument, extraArgument);
}
}
您可以在AddArguments
方法中从原始测试用例复制类别。
如前所述,最好有不同的测试用例数据实例,因为并行执行测试时可能会出现问题。
方法的名称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);
}
创建一个新的测试用例源方法,该方法从原始方法的相同位置提取数据,并进行修改。谢谢!我最终会使用它。但由于我能够做tcd..Returns(“aaa”),我认为没有理由不做tcd.AddOneMoreArg(“new”)。如果可能的话,我宁愿使用这个选项。@Jeni,你可以创建自己的扩展方法-检查更新的应答OK!这看起来几乎是我要找的100%。我唯一的问题是这样会丢失原始TestCaseData的其他属性。在我上面的示例代码中,这就是类别。是否有一种方法可以透明地从源代码复制所有其他内容,或者我应该针对类别、预期结果等逐个显式地执行此操作@Jeni,您可以使用相同的扩展方法复制类别,请检查更新的答案