Jump to content

Macros/ScriptForge/HowToUnitTestingBASICdevlep

From The Document Foundation Wiki


How to unit testing a Basic development

Authored by Jean-Pierre Ledure.

DEFINITIONS

  1. 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.
  2. 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.
  3. 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

  1. Create a new Calc document.
  1. Open the Basic IDE
  2. Create a new library in the document called 'UniTests'
  3. Copy and paste the AllTests.vb code in a module called 'AllTests'
  4. Copy and paste the CalcTest.vb code in a module called 'CalcTest'
  5. Check the constants in lines 13-14 of the AllTests module
  6. Run AllTests.Main()
Detailed test report from execution of test.
Execution of test produces a detailed test report for BASIC development.

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

See also