虽然你当然不能测试每的可能性,你应该在至少测试代码中考虑的可能性。
:
你的榜样,在传递给方法的字符串不得超过8个字符(这是一个密码
可怕要求的方式),该方法可能会是这个样子
所以
public bool IsPasswordCorrect(string password)
{
if (password.Length > 8)
throw new ArgumentException("Password must not be greater than 8 characters.");
return password == SomeKnownPassword;
}
目标应该是100%的代码覆盖率。这意味着每行代码实际上应该有至少一个相应的测试。因此,如果只考是针对“快乐路径”(字符串,其不大于8个字符),然后throw
线从来没有测试。
该行代码是为响应需求而存在的,因此需要测试该需求。在这种情况下,你有几个测试:
[TestMethod]
public void MatchingPasswordsShouldBeAllowed()
{
// set the known password
// set the passed password
// call the method
// assert that the method returned true
}
[TestMethod]
public void NonMatchingPasswordsShouldNotBeAllowed()
{
// set the known password
// set the passed password to something else
// call the method
// assert that the method returned false
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void PasswordsShouldNotBeGreaterThanEightCharacters()
{
// set the known password
// set the passed password to something too long
// call the method
// assert that an exception was thrown
}
公告的测试方法的名称。他们听起来像要求。这个想法是,所述的要求应该分解成实际的规格。业务要求是:
但那里有隐含的要求是什么?要求如:
- 提供的密码与已知密码匹配应导致身份验证。
- 提供的密码与已知密码不匹配不应导致认证。
毕竟,该方法是做所有这些事情。如果该方法正在做某件事,那么应该测试一些东西。最终,代码所做的一切应该至少有一个映射到需求的相应测试。
事实上,如果测试写得不错,他们开始成为的要求。这很好,因为这意味着有问题的知识(需求)可以保存在一个地方(测试),而不是多个不同的地方(测试,代码,文档,白板等)。
如果有一行代码没有被测试执行,那么为什么那行代码在那里?如果没有测试,那就没有要求了。如果没有要求,请将其移除。
您有没有想过[角落或边缘情况](http://en.wikipedia.org/wiki/Corner_case)您的故事要求? – Akim 2012-07-22 17:53:37