ThrowTheSwitch / CMock

CMock - Mock/stub generator for C
http://throwtheswitch.org
MIT License
652 stars 269 forks source link

Question: Can I use CMock to assert a mocked function is not called? #432

Closed larshei closed 1 year ago

larshei commented 1 year ago

I am currently writing a function which parses an incoming data stream.

Whenever a linefeed is found, a callback should be called, passing in a line.

Here is a test that shows the behaviour when a line break is found:

#include "unity.h"
#include <stdio.h>
#include "parser.h"
#include "mock_callback.h"

void test_parse_single_line__should_call_callback_with_string_up_to_linefeed_char(void) {
  char line[] = "Hello\rWorld!";
  char expected_call_parameter[] = "Hello";

  // we expect the callback to be called with just "Hello" (no \r) and a length of
  // "Hello" - 1 ( -1 because anything in "" automatically has \0 appended)
  callback_Expect(expected_call_parameter, sizeof(expected_call_parameter) - 1);
  parse(line, sizeof(line), callback);
}

Now I want to test what happens if no linefeed char is found in the input. In this case, as we did not complete a line, I would like to not call the callback function:

void test_parse_no_linefeed__should_not_call_callback(void) {
  char line_without_line_break[] = "Hello!";

  // HOW TO?: make sure callback() is not being called.
  parse(line_without_line_break, sizeof(line_without_line_break), callback);
}

I went through the temp_sensor example and the docs, but I could not figure out how to do this. Is there a way to check that a mocked function was not called?

Letme commented 1 year ago

Setup and Verify check if mocked functions were called or not. So if you do not "Expect" a function then the test will pass when no function is called, and if you do not "Expect" and function is called, it will fail the test case.

larshei commented 1 year ago

Ah I see.

So a mocked function being called would immediately fail the test, if not expected, meaning having 0 Expect functions means the function is called 0 times when the test passes.

Thanks!