使用,把包下載,然后解到一個目錄,運行install.exe,打開VB??梢园l現可以新建CoMunit Test Project的工程。有兩個文件frmTestRunner的form,TCTestContainer是測試類。下面我們看一下如何使用comunit。先下載測試代碼。
這個代碼是測試二進制文件在javascript:tagshow(event, '%CA%FD%BE%DD%BF%E2');" href="javascript:;" target=_self>數據庫里的存取。有關二進制代碼在數據庫里存取的技術問題,請看另一篇文章。用什么辦法來確定代碼是正確工作了呢?答案當然是單元測試。
測試代碼很簡單,但的確很有效,它保證這段代碼是正確的工作了。
' COMUnit 1.1 - TestContainer Class
Option Explicit ' Interface declaration ' Return the name of the different test case methods in this test container ' Run the specified test case methods in this test container 'Initialize the test fixture ' TODO: initialize your test fixture here 'Destroy the test fixture 'Public Sub testSampleMethod(oTestResult As TestResult) |
寫單元測試代碼很簡單,只要完成幾個函數就可以了。
Public Property Get ITestContainer_TestCaseNames() As Variant() ' TODO: add the names of your test methods as a parameter into the Array() function ITestContainer_TestCaseNames = Array("TestFields") End Property |
第一個,ITestContainer_TestCaseNames。是測試函數的列表,ITestContainer_TestCaseNames = Array("TestFields"),TestFields就是函數名,要測試這個函數,就寫在這個數組里。
Public Sub ITestContainer_RunTestCase(oTestCase As ITestCase, oTestResult As TestResult) On Error GoTo ErrorHandler InvokeHook Me, oTestCase.Name, INVOKE_FUNC, oTestResult ' CallByName Me, oTestCase.Name, VbMethod, oTestResult Exit Sub ErrorHandler: oTestResult.AddError Err.Number, Err.Source, Err.Description End Sub |
這個函數是自動生成的,不用修改。
'在測試開始時自動調用 End Sub |
這個函數是每一個測試函數運行時自動調用的,可以在這個函數中初始化測試的內容。
Public Sub ITestContainer_TearDown() End Sub |
這個函數是每個測試函數結束時,自動運行,在這個函數中可以釋放在測試中使用的資源。
'Public Sub testSampleMethod(oTestResult As TestResult) ' TODO: add your test code here 'End Sub Private Sub TestFieldtoFile(oTestResult As TestResult) oTestResult.Assert BinTest.FieldToFile(DesFile, k!thefile), "導出到文件不成功" End Sub Private Sub TestFiletofield(oTestResult As TestResult) oTestResult.Assert BinTest.fileTofield(SourceFile, k!thefile), "導入到數據庫不成功" End Sub Public Sub TestFields(oTestResult As TestResult) TestFiletofield oTestResult TestFieldtoFile oTestResult oTestResult.Assert FileLen(SourceFile) = FileLen(DesFile), "文件不相符!" End Sub |
這三個函數就是測試函數。TestFields是公共測試函數,另兩個函數由TestFields調用。先把文件導入到數據庫,再從數據庫把文件導出到文件中,最后比較兩個文件是否相同。
下面我們來看怎么在VB中使用。打開工程,在VB工具菜單中選項中把修改錯誤捕獲的設置。改成遇到未處理錯誤的中斷。如下圖所未。
運行程序,出現下面這個界面。下面可以看到有一個類可以測試,選擇這個類,看Test Case列表,就能看到TestFields這個測試函數了?!“碦unTest。如果通過測試,就能說明這兩段代碼就達成目的了。
下面我們來看出現錯誤的情況。把函數TestField中TestFieldtoFile oTestResult注釋掉。這樣就只導入文件,不進行導出文件??匆幌翿un Tests的結果,如下圖所未:
可以看到,progress條變成紅色,表示運行過程中有出錯的測試。下錯誤列表中列出出現錯誤函數名及錯誤內容,可以雙擊出現某條單獨的錯誤說明。下面狀態條有測試的統計信息。
我們看上面的簡單的39行代碼,就能保證另一個類代碼的正確性,并且,以后可以進行任意的修改,只要代碼能夠通過測試就能保證修改的沒有產生意外的錯誤。
原文轉自:http://www.anti-gravitydesign.com