雖然你當然不能測試每的可能性,你應該在至少測試代碼中考慮的可能性。
:
你的榜樣,在傳遞給方法的字符串不得超過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