有没有一种方法可以将NUnit TestCase属性与可选参数一起使用



我正在尝试运行一些测试用例,但我需要将其中一个参数设置为可选参数。

我尝试了以下操作,但NUnit忽略了测试,并打印了以下"忽略:提供了错误数量的参数">

[TestCase(Result = "optional")]
[TestCase("set", Result = "set")]
public string MyTest(string optional = "optional")
{
return optional;          
}

是否可以使用可选参数运行测试用例?

在这种情况下只进行2次测试,nunit中不支持可选的参数:

[TestCase("set", Result = "set")]
public string MyTest(string optional)
{
return optional;          
}
[TestCase(Result = "optional")]
public string MyTest()
{
return MyTest("optional");          
}

听起来你试图在这里测试两个不同的东西,所以我倾向于使用两个单独的测试,正如peer已经指出的那样。

如果出于某种原因,您确实需要或希望在一个测试中使用null或常量作为参数,并在测试中添加代码来处理它。注意不要让测试中的逻辑过于复杂(理想情况下,测试中不应该有任何逻辑)。

const string NO_VALUE = "Just a const to identify a missing param";
[TestCase(null, Result = "optional")] // Either this... 
[TestCase(NO_VALUE, Result = "optional")] // or something like this
[TestCase("set", Result = "set")]
public void MyTest(string optional)
{
// if(optional == null)  // if you use null
if(optional == NO_VALUE) // if you prever the constant
{
// Do something
}
else{
// Do something else
}        
}

您可以使用JSON作为测试用例:

[Test]
[TestCase(@"{
'Param1': 123,
'Param3': true,
'Param5': 'Abc'
}")]
public void MyTest(string json)
{
var testParams = JsonConvert.DeserializeObject<ParamsModel>(json);
}
private class ParamsModel
{
public int Param1 { get; set; }
public string? OptionalParam2 { get; set; } = null;
public string Param3 { get; set; }
public string? OptionalParam4 { get; set; } = null;
public string Param5 { get; set; }
}

最新更新