Test-Driven Development and Visual Studio Team System

Test-Driven Development (TDD)是一個在軟體開發週期中比較容易掌控軟體品質的開發方法, 這種開發模式可以確保所有的requirement都有相對應的functional code, 也不會有多餘而不必要的code存在於產品中. TDD也是實行 Extreme Programming 的其中一種core practice. 而利用Team System中的test framework, 就可以幫助開發團隊實行TDD.

所謂的Test-Driven Development, 顧名思義, 就是先有test case, 利用這些test case去驅動各種functionality development. 依照 Kent Beck 的定義, 有兩個基本的rules:

1. Write new code only if an automated test has failed

2. Eliminate duplication

其實行的方法, 大致上是由test team先由requirements中開發出test case, 然後developer (或development team) 再去開發functions來滿足這些test case,讓所有test cases pass. 接著test team再針對functions寫新的test case, 這些新的test case可以根據修改過的requirement和現存的function來寫, 並確定這些新增加的test cases會fail. 然後developer根據這些failed test cases來修改原來的functions. 這樣的過程不斷循環直至最後沒有test cases fail為止. 所以我們可以歸納出以下簡單的TDD步驟:

1. 撰寫test case

2. 撰寫或修改functional code

3. 撰寫新的test case

4. 利用1.和3.步驟中test case測試functional code. 反覆執行2.到4.步驟直到所有test case pass為止

5. 重整 (refactor) functional code以去除不必要的code.

這樣的開發模式, 讓developer能專注於解決requirement, 也確保每一段code都有相對的unit test, 而經由automated test framework, 每一個test都是可以重覆實行的, 最終產品開發完成時品質也相對穩定. 值得注意的是, 並非實行了TDD, 其它的測試就不用做了, 諸如load test, integration test, functional test還是要在開發過程中同時執行才能確保產品品質.

所以要有效率的執行這樣的開發流程, 自動化測試的framework是有力且必要的工具. VSTS中就提供了一組好用的framework來幫助開發團隊實行TDD. 在VSTS裏, 現在多增加了一組project template: Test Project. Create一個新的test project後, 就可以依照requirement來撰寫test method. 例如我的requirement要撰寫一個回傳hello world的method, 我可以先在我的test project裏, 填入以下的test class和test mehotd:

[TestClass]
public class Test1
{
[TestMethod]
public void HelloWorldTest()
{
string expected = "Hello World";
Assert.AreEqual(expected, HelloWorld.HelloWorld());
}
}   

然後compile執行之. 由於我們並未曾撰寫過HelloWorld這個class和HelloWorld()這個method, 我們的test case會fail. Developer根據這個failed test case撰寫了HelloWorld class和HelloWorld() method後, tester再執行上述那個HelloWorldTest, 測試developer寫的functional code是否能讓test case pass. 反覆執行上述步驟直到functional code pass所有的test case為止. VSTS Quality Tools還可以檢視test case的code coverage以確保每一段functional code都有完整的測試覆蓋. Developer也可以利用VSTS中refactoring的工具, 重整所有的functional code來移除不必要的code或修改之前的code. 同理, 如果test case有錯誤或需求有改變, 也可以利用refactoring工具來修改test code.

另外VSTS中的Test Manager, 則可以管理所有的test cases, 依照不同的需求執行部分或所有的test cases, 並監控管理所有的測試結果.