你是否会写两个单元测试?一个用于值为 Null,另一个用于值为空字符串?同样的方式适用于 string.IsNullOrWhiteSpace() 吗?
通常情况下,您需要测试所有可能的输入类别(空、空字符串、空格和非空格),以确保输出正确。
这意味着要测试 String.IsNullOrEmpty()
的两个选项和 String.IsNullOrWhiteSpace()
的三个选项。
NUnit
测试用例来测试这些排列组合。这将为您提供三种不同检查的覆盖范围,而不会重复测试代码。[TestCase("")]
[TestCase(null)]
public class SomeTest(string stringValue)
{
Assert.Throws<ArgumentException>(()=> CheckIfNullOrEmpty(stringValue));
}
public void CheckIfNullOrEmpty(string val)
{
if(string.IsNullOrEmpty(val))
{
throw new ArgumentException();
}
}
编程方面的内容,返回翻译文本:
关于需要编写多少单元测试没有固定规则,但是我建议您至少进行以下4种测试:
被测试的代码:
public string MyMethod(string s){
//Do stuff
if (string.IsNullOrWhitespace(s)){
return "failed";
} else {
return "passed";
}
}
因为你正在测试一个黑盒子,所以需要考虑以下情况:
NULL
""
" "
"A"
你可能还需要做更多的工作,例如:
" A "
"AAAA"
etc
在进行单元测试时,主要关注点应该是“好”的情况。因此,我希望通过的测试比失败的测试更多。