1.建立單元測試項目
2.建立完成後,新建項目會自動添加「Microsoft.VisualStudio.QualityTools.UnitTestFramework」的引用,該引用用於單元測試
3.新建項目中自動生成一個默認測試文件「UnitTest1.cs」,內容以下圖
[TestClass]:爲表示該類爲測試類。
[TestMethod]:爲測試方法,如測試類下有多個測試方法,開始執行測試用例時,自上往下挨個執行測試方法。
4.添加本身的測試方法,並使用測試類自帶的斷言方法「Assert.AreEqual(expected, actual); 」,用於比對結果是否正確。
expected:爲預期結果
actual:爲真實結果
5.開始執行測試用例
執行測試用例有三種方式:
- 將測試用例項目設置爲啓動項,和日常項目啓動是同樣的,F5啓動,能夠在測試用例方法出加個斷點,方便查看
- 在測試用例方法出右鍵「運行測試」,以下圖:
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
也能夠使用vs2010頂部菜單欄下的「測試」按鈕進行運行或調試。
運行結果:會提示是否成功,和失敗緣由
如今將expected結果設置爲3,運行成功以下圖:
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
將expected結果設置爲1,運行失敗以下圖
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
如VS2010上安裝Reshape,右鍵出現「Run Unit Tests」和「Debug Unit Tests」按鈕。分別表示,執行測試用例,和debug下執行測試用例。
使用Reshape的測試用例啓動按鈕,有一個好處是能夠使用Debug模式,如測試項目不是啓動項,那這個功能尤其重要了。
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
運行結果:
預期只爲1
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
預期值爲3
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
附加測試屬性單元測試
"附加測試屬性"。默認都是被註釋掉的,只要咱們取消註釋就能夠使用了。這個功能的加入,很大程度上是爲了增長測試的靈活性。具體的屬性有:測試
[ClassInitialize()]在運行類的第一個測試前先運行代碼(使用該屬性的方法,必須是參數爲TestContext的帶參方法)debug
[ClassCleanup()]在運行完類中的全部測試後再運行代碼3d
[TestInitialize()]在運行每一個測試前先運行代碼調試
[TestCleanup()]在運行完每一個測試後運行代碼日誌
如在執行測試時,將測試執行時間輸入到日誌中,代碼以下blog
![](http://static.javashuo.com/static/loading.gif)