Macros/ScriptForge/HowToUnitTestingBASICdevlep
Appearance
< Macros | ScriptForge
TDF LibreOffice Document Liberation Project Community Blogs Weblate Nextcloud Redmine Ask LibreOffice Donate
How to unit testing a Basic development
Authored by Jean-Pierre Ledure.
DEFINITIONS
- A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. In the UnitTest service, a test case is represented by a single Basic
Sub
whose name starts with a common prefix (the default is "Test_"). The test case fails if one of the AssertXXX methods returns False. - A test suite is a collection of test cases that should be executed together. All test cases of a test suite are stored in a single Basic module. A test suite may implement the SetUp and TearDown methods to prepare for test cases in its module.
- A full unit test consists of a set of test suites in the same Basic library.
The example implements a fictitious unit test of ScriptForge services. Only one test suite is considered: testing the Calc service. The 2 considered test cases are the SetArray and SetValue methods.
How to run in BASIC
- Create a new Calc document.
- Open the Basic IDE
- Create a new library in the document called 'UniTests'
- Copy and paste the AllTests.vb code in a module called 'AllTests'
- Copy and paste the CalcTest.vb code in a module called 'CalcTest'
- Check the constants in lines 13-14 of the AllTests module
- Run AllTests.Main()
Code
REM SCRIPTFORGE WIKI EXAMPLE
REM How to make unit tests for Basic code ?
REM Minimal required version: LibreOffice 7.6
REM Used services
REM UnitTests, Calc, Exception
Option Explicit
REM The orchestrator
REM ----------------
REM Code stored in library UnitTests, module AllTests
Const library = "UnitTests"
Const testsuite = "CalcTest"
REM Next Sub runs all testsuites in full mode.
Sub Main()
Dim test As Object
Dim exc As Object
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
Set exc = CreateScriptService("Exception")
exc.ConsoleClear()
exc.Console(modal := False)
Set test = CreateScriptService("UnitTest", ThisComponent, library)
With test
.RunTest(testsuite := testsuite)
Select Case .ReturnCode
' 0 - Test finished without errors or test not started
' 1 - An assertion within a test case returned False
' 2 - A SkipTest was issued by the Setup method or by one of the test cases.
' 3 - Abnormal end of test
Case 0
MsgBox "Tests OK !"
Case > 0
MsgBox "Tests failed with return code = " & .ReturnCode
End Select
.Dispose()
End With
End Sub