Next: , Previous: Test Fixtures, Up: Test Fixtures



4.3.1 Test Fixture Examples

We create a test fixture in Check as follows:

  1. Define global variables, and functions to setup and teardown the globals. The functions both take void and return void. In our example, we'll make five_dollars be a global created and freed by setup() and teardown() respectively.

  2. Add the setup() and teardown() functions to the test case with tcase_add_checked_fixture(). In our example, this belongs in the suite setup function money_suite.
  3. Rewrite tests to use the globals. We'll rewrite our first to use five_dollars.

Note that the functions used for setup and teardown do not need to be named setup() and teardown(), but they must take void and return void. We'll update check_money.c as follows:

     --- tests/check_money.6.c	2006-11-21 18:06:36.892245648 -0500
     +++ tests/check_money.7.c	2006-11-21 18:06:36.925240632 -0500
     @@ -2,15 +2,26 @@
      #include <check.h>
      #include "../src/money.h"
      
     +Money *five_dollars;
     +
     +void
     +setup (void)
     +{
     +  five_dollars = money_create (5, "USD");
     +}
     +
     +void
     +teardown (void)
     +{
     +  money_free (five_dollars);
     +}
     +
      START_TEST (test_money_create)
      {
     -  Money *m;
     -  m = money_create (5, "USD");
     -  fail_unless (money_amount (m) == 5, 
     +  fail_unless (money_amount (five_dollars) == 5,
      	       "Amount not set correctly on creation");
     -  fail_unless (strcmp (money_currency (m), "USD") == 0,
     +  fail_unless (strcmp (money_currency (five_dollars), "USD") == 0,
      	       "Currency not set correctly on creation");
     -  money_free (m);
      }
      END_TEST
      
     @@ -38,6 +49,7 @@
      
        /* Core test case */
        TCase *tc_core = tcase_create ("Core");
     +  tcase_add_checked_fixture (tc_core, setup, teardown);
        tcase_add_test (tc_core, test_money_create);
        suite_add_tcase (s, tc_core);