Search code examples
cmockingembeddedtddgoogletest

How to count the number of times the real function has been called using a mocking framework in C


I'm starting to use TDD for writing embedded C software and I'm using Google Test as my testing framework. I just realized a situation that doesn't seem to be covered on any mocking tutorials: I want to count how many times a given REAL function has been called.

So, let's say that I'm developing some code that uses a library called LIB_A, which in turn uses another library called LIB_B.

normally, I would mock LIB_B and have a test like so:

TEST(MyCodeTest, CanDoSomething) {
  Mock_LIB_B_Class mock_object;
  MyClass my_obj;

  // We expect that doSomething will call SomeMethod at least once
  EXPECT_CALL(mock_class, SomeMethod()).Times(AtLeast(1));

  // Checks for the expected return
  EXPECT_EQ(0, my_obj.doSomething());
}

OK, that's all fine and dandy. Now here's my question: what if I don't have to mock LIB_A, but mock LIB_B. how can I count the number of times SomeMethod gets called? Because mocking frameworks make it easy to create mock functions that don't actually have a real implementation.

I'm thinking that I could use a fake for LIB_A, so the calls would be countable. I'm thinking about using either Google Mock or Fake Function Framework.

Thanks!


Solution

  • You don't need any mock framework to accomplish this. You can use gcov/lcov/genhtml.

    By including the gcc flags -fprofile-arcs and -ftest-coverage, and the linker flag -lgcov, your executable will generate runtime information about which lines of code were executed and by using the aforementioned tools you can easily generate a set of html files which will show you a list of functions including their call count.

    After executing your test, do:

    gcov maintest.c
    lcov --capture --directory . --output-file maintest.info
    genhtml maintest.info --output-directory html
    

    Then open index.html, choose a file and click the functions button in the top bar, next to the file name. It will look something like this:

    enter image description here