在使用過NUnit後,一直想在VB6中使用一下單元測試工具,目前比較流行的是VBUnit和ComUnit,我比較喜歡ComUnit主要是它是開源的,當然用起來比較爽了,可以在http://comunit.sourceforge.net/進行下載。
ComUnit使用比較簡單,注意下邊幾點後就可以使用了。
' COMUnit 1.1 - TestRunner form
Option Explicit
' Initialize the TestRunner control
Private Sub Form_Load()
' TODO: add instances of your TestContainer classes to the UnitRunner control
' e.g. UnitRunner1.AddTestContainer New TCTestContainer
'************************************************
'必須向UnitRunner添加一個控制對象,別的不需要修改
UnitRunner1.AddTestContainer New TCTestContainer
'************************************************
End Sub
' Run the tests selected in the UnitRunner
Private Sub btnRun_Click()
UnitRunner1.Run
End Sub
' Close the form
Private Sub btnClose_Click()
Unload Me
End Sub
' Resize the UnitRunner control and the buttons on the form
Private Sub Form_Resize()
UnitRunner1.Move 0, 0, ScaleWidth, PosInt(ScaleHeight - btnClose.Height - 50)
btnClose.Move PosInt(ScaleWidth - btnClose.Width), PosInt(ScaleHeight - btnClose.Height)
btnRun.Move PosInt(ScaleWidth - btnClose.Width - btnRun.Width - 100), PosInt(ScaleHeight - btnRun.Height)
End Sub
Private Function PosInt(iValue) As Integer
PosInt = IIf(iValue > 0, iValue, 0)
End Function
' COMUnit 1.1 - TestContainer Class
'建議類的首碼為TC
Option Explicit
' Interface declaration
Implements ITestContainer
' Fixture Member Variables
' TODO: specify your TestContainer test fixture member variables here
' Return the name of the different test case methods in this test container
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("TestString", "TestLong")
End Property
' Run the specified test case methods in this test container
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
'Initialize the test fixture
Public Sub ITestContainer_Setup()
' TODO: initialize your test fixture here
End Sub
'Destroy the test fixture
Public Sub ITestContainer_TearDown()
' TODO: destruct your test fixture here
End Sub
'Public Sub testSampleMethod(oTestResult As TestResult)
' TODO: add your test code here
'End Sub
Public Sub TestString(oTestResult As TestResult)
oTestResult.Assert "String" = "String", "字串不相等"
End Sub
Public Sub TestLong(oTestResult As TestResult)
oTestResult.AssertEqualsLong 1, 456, "數值不相等"
End Sub
在表單中要將Runner和類進行綁定,建議的類名首碼為TC,新增的測試函數一定要在ITestContainer_TestCaseNames中進行註冊,新增的測試函數一定要有oTestResult As TestResult這個聲明,而且只能有這麼一個聲明。
還有就是要在IDE的選項中,將錯誤捕獲改為“遇到未處理的錯誤時中斷”就可以享受VB6下邊的單元測試了。
參考文章:
http://champion.ewuxi.com/old/XP/xppractice/vbunit.htm
http://www.soho-works.net/BLOG/313.asp
http://comunit.sourceforge.net/?page=tutorial.html