A failing test
A test earns its keep the day it fails. Here WordCount counts the spaces
instead of the words, and the test catches it:
#include once "fbcunit.bi"
'' Meant to count the words in s -- but it counts the spaces.
function WordCount( byval s as ustring ) as int32
dim as int32 n = 0
for i as int32 = 1 to len( s )
if mid( s, i, 1 ) = " " then n += 1
next
return n
end function
SUITE( words )
TEST( counts_words )
CU_ASSERT_EQUAL( WordCount( "" ), 0 )
CU_ASSERT_EQUAL( WordCount( "one two three" ), 3 )
CU_ASSERT_EQUAL( WordCount( "single" ), 1 )
END_TEST
END_SUITE
end iif( fbcu.run_tests( ), 0, 1 )
Output
failing.tiko(15) : error : TESTS.WORDS.COUNTS_WORDS CU_ASSERT_EQUAL(WordCount( "one two three" ),3)
failing.tiko(16) : error : TESTS.WORDS.COUNTS_WORDS CU_ASSERT_EQUAL(WordCount( "single" ),1)
SUMMARY
Asserts Passed Failed Suite Tests
-------- -------- -------- -------------------------------------- --------
3 1 2 words 1
-------- -------- -------- -------------------------------------- --------
3 1 2 Total 1
The program exits with code 1.
Each failed assertion is printed before the summary with three things you need
to find it: the file and line, the test's full name (TESTS.WORDS.COUNTS_WORDS,
the suite and test in capitals), and the assertion as it was written. The first
check passed, because the empty string has no spaces either; the other two
failed.
The summary's Failed column is the number of failed assertions, not of
failed tests, and run_tests returns false when it is anything but zero.
That is why the exit code is 1: a build script that runs the tests stops here.
Write the test that shows a bug before you fix the bug. When the test passes, you know the fix works, and the test stays to make sure the bug does not come back.
Activities
- Fix
WordCount(count the starts of words, not the spaces) and run the tests again. - Add
CU_ASSERT_EQUAL( WordCount( "two spaces" ), 2 )and check that your fix handles it.