Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Testing

A program that compiles is a program the compiler could read. Whether it does what you meant is a separate question, and a test answers it every time you build. tiko ships a unit-test library, fbcunit.bi: tests are blocks of code that check results with assertion macros, grouped into suites, and one call runs them all and prints a summary.

'' A procedure, and the tests that pin its behaviour down.
#include once "fbcunit.bi"

function Clamp( byval v as int32, byval lo as int32, _
                byval hi as int32 ) as int32
    if v < lo then return lo
    if v > hi then return hi
    return v
end function

SUITE( clamping )
    TEST( inside_the_range )
        CU_ASSERT_EQUAL( Clamp( 5, 0, 10 ), 5 )
    END_TEST

    TEST( on_the_edges )
        CU_ASSERT_EQUAL( Clamp( 0, 0, 10 ), 0 )
        CU_ASSERT_EQUAL( Clamp( 10, 0, 10 ), 10 )
    END_TEST

    TEST( outside_the_range )
        CU_ASSERT_EQUAL( Clamp( -3, 0, 10 ), 0 )
        CU_ASSERT_EQUAL( Clamp( 99, 0, 10 ), 10 )
    END_TEST
END_SUITE

'' Run every test, print the summary, and exit 0 only if all passed.
end iif( fbcu.run_tests( ), 0, 1 )

Output


SUMMARY

 Asserts    Passed    Failed  Suite                                      Tests
--------  --------  --------  --------------------------------------  --------
       5         5         0  clamping                                       3
--------  --------  --------  --------------------------------------  --------
       5         5         0  Total                                          3
  • #include once "fbcunit.bi" brings in the library. It is a header, not a module, so it is included rather than imported.
  • SUITE( clamping ) … END_SUITE groups related tests. Each TEST( name ) … END_TEST is one test, and its body is ordinary code.
  • CU_ASSERT_EQUAL( a, b ) records a pass when a = b and a failure otherwise. The summary counts both, per suite.
  • fbcu.run_tests( ) runs every test, prints the summary, and returns true only if every assertion passed. end iif( …, 0, 1 ) turns that into the program's exit code, which is what a build script or a CI job checks.

There is no separate test command: a test program is an ordinary program, built with tiko firsttests.tiko and run like any other.

Name a suite after the behaviour it checks, clamping, not after the procedure it tests, Clamp. A suite is a namespace, and inside a suite called clamp the name Clamp would mean the suite, not the function.

Activities

  1. Add a test that Clamp( 5, 5, 5 ) is 5.
  2. Break Clamp on purpose and watch the summary and the exit code change.