diff options
| author | mo khan <mo.khan@gmail.com> | 2020-06-14 21:57:08 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-06-14 21:57:08 -0600 |
| commit | c687bfe6008bc7a2870e676873c87cd733ebc444 (patch) | |
| tree | e1c9728273b38a1fb8891d3402534607ab380a9b | |
| parent | fd9bfc42af1ae0a070558524d7e384eede8d9083 (diff) | |
Add test using mocks
| -rw-r--r-- | words.c | 12 | ||||
| -rw-r--r-- | words.h | 1 | ||||
| -rw-r--r-- | words_test.c | 21 |
3 files changed, 34 insertions, 0 deletions
@@ -1,3 +1,4 @@ +#include <stdlib.h> #include <string.h> int split_words(char *sentence) { @@ -11,3 +12,14 @@ int split_words(char *sentence) { } return count; } + +void words(const char *sentence, void (*callback)(const char *, void *), void *memo) { + char *words = strdup(sentence); + int word_count = split_words(words); + char *word = words; + while (word_count-- > 0) { + (*callback)(word, memo); + word = word + strlen(word) + 1; + } + free(words); +} @@ -1 +1,2 @@ int split_words(char *sentence); +void words(const char *sentence, void (*callback)(const char *, void *), void *memo); diff --git a/words_test.c b/words_test.c index 651ee6f..c7af6b9 100644 --- a/words_test.c +++ b/words_test.c @@ -1,4 +1,5 @@ #include <cgreen/cgreen.h> +#include <cgreen/mocks.h> #include "words.h" #include <string.h> @@ -22,9 +23,29 @@ Ensure(Words, converts_spaces_to_zeroes) { free(sentence); } +void mocked_callback(const char *word, void *memo) { + mock(word, memo); +} + +Ensure(Words, invokes_callback_once_for_single_word_sentence) { + expect(mocked_callback, + when(word, is_equal_to_string("Word")), when(memo, is_null)); + words("Word", &mocked_callback, NULL); +} + +Ensure(Words, invokes_callback_for_each_word_in_a_phrase) { + expect(mocked_callback, when(word, is_equal_to_string("Birds"))); + expect(mocked_callback, when(word, is_equal_to_string("of"))); + expect(mocked_callback, when(word, is_equal_to_string("a"))); + expect(mocked_callback, when(word, is_equal_to_string("feather"))); + words("Birds of a feather", &mocked_callback, NULL); +} + TestSuite *words_tests() { TestSuite *suite = create_test_suite(); add_test_with_context(suite, Words, returns_word_count); add_test_with_context(suite, Words, converts_spaces_to_zeroes); + add_test_with_context(suite, Words, invokes_callback_once_for_single_word_sentence); + add_test_with_context(suite, Words, invokes_callback_for_each_word_in_a_phrase); return suite; } |
