What happens if we pass -1 as the amount in
money_create()? What should happen? Let's write a unit test.
Since we are now testing limits, we should also test what happens when
we create Money where amount == 0. Let's put these in a
separate test case called “Limits” so that money_suite is
changed like so:
--- tests/check_money.3.c 2006-11-21 18:06:36.825255832 -0500
+++ tests/check_money.6.c 2006-11-21 18:06:36.892245648 -0500
@@ -14,6 +14,23 @@
}
END_TEST
+START_TEST (test_money_create_neg)
+{
+ Money *m = money_create (-1, "USD");
+ fail_unless (m == NULL,
+ "NULL should be returned on attempt to create with "
+ "a negative amount");
+}
+END_TEST
+
+START_TEST (test_money_create_zero)
+{
+ Money *m = money_create (0, "USD");
+ fail_unless (money_amount (m) == 0,
+ "Zero is a valid amount of money");
+}
+END_TEST
+
Suite *
money_suite (void)
{
@@ -24,6 +41,12 @@
tcase_add_test (tc_core, test_money_create);
suite_add_tcase (s, tc_core);
+ /* Limits test case */
+ TCase *tc_limits = tcase_create ("Limits");
+ tcase_add_test (tc_limits, test_money_create_neg);
+ tcase_add_test (tc_limits, test_money_create_zero);
+ suite_add_tcase (s, tc_limits);
+
return s;
}
Now we can rerun our suite, and fix the problem(s). Note that errors in the “Core” test case will be reported as “Core”, and errors in the “Limits” test case will be reported as “Limits”, giving you additional information about where things broke.
--- src/money.5.c 2006-11-21 18:06:37.522149888 -0500
+++ src/money.6.c 2006-11-21 18:06:37.588139856 -0500
@@ -10,6 +10,11 @@
Money *
money_create (int amount, char *currency)
{
+ if (amount < 0)
+ {
+ return NULL;
+ }
+
Money *m = malloc (sizeof (Money));
if (m == NULL)
{