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

Assertions

Each assertion macro checks one thing and records the result. Choosing the macro that says what you mean makes a failure message easier to read.

#include once "fbcunit.bi"

function Initials( byval first as ustring, _
                   byval last as ustring ) as ustring
    return ucase( left( first, 1 ) & left( last, 1 ) )
end function

SUITE( assertions )
    TEST( truth )
        CU_ASSERT( len( Initials( "ada", "lovelace" ) ) = 2 )
        CU_ASSERT_TRUE( Initials( "ada", "lovelace" ) = "AL" )
        CU_ASSERT_FALSE( Initials( "ada", "lovelace" ) = "al" )
    END_TEST

    TEST( equality )
        CU_ASSERT_EQUAL( Initials( "alan", "turing" ), "AT" )
        CU_ASSERT_NOT_EQUAL( Initials( "alan", "turing" ), "TA" )
    END_TEST

    TEST( floating_point )
        '' 0.1 + 0.2 is not exactly 0.3; compare within a tolerance.
        dim as float64 sum = 0.1 + 0.2
        CU_ASSERT_DOUBLE_EQUAL( sum, 0.3, 1e-12 )
        CU_ASSERT_NOT_EQUAL( sum, 0.3 )
    END_TEST
END_SUITE

end iif( fbcu.run_tests( ), 0, 1 )

Output


SUMMARY

 Asserts    Passed    Failed  Suite                                      Tests
--------  --------  --------  --------------------------------------  --------
       7         7         0  assertions                                     3
--------  --------  --------  --------------------------------------  --------
       7         7         0  Total                                          3
MacroPasses when
CU_ASSERT( c )c is true
CU_ASSERT_TRUE( c ), CU_ASSERT_FALSE( c )c is true, or false
CU_ASSERT_EQUAL( a, b )a = b
CU_ASSERT_NOT_EQUAL( a, b )a <> b
CU_ASSERT_DOUBLE_EQUAL( a, e, g )a is within g of e
CU_FAIL( msg )never: marks code a test must not reach

The floating_point test shows why CU_ASSERT_DOUBLE_EQUAL exists. 0.1 + 0.2 is not exactly 0.3 in binary floating point, so CU_ASSERT_NOT_EQUAL( sum, 0.3 ) passes. A test of a computed float64 compares it within a tolerance that fits the calculation.

A failed assertion does not stop its test: the test carries on, and every failure is listed before the summary. That is what lets one test hold several related checks.

Activities

  1. Add CU_ASSERT_EQUAL( sum, 0.3 ) to floating_point and read the failure.
  2. Tighten the tolerance to 1e-20 and see whether the test still passes.