Search code examples
c++cunit-testinggoogletest

How to test C++ code when using C functions


I wrote a c++ class, this class uses the c function library written by a third party.

extern "C" {
#include "nats/nats.h"
}

class NatsConnection {
  public:
  void Connect() {
    natsConnection_Connect(&natsConnection_, natsOptions_);
    natsConnection_SubscribeSync(&natsSubscription_, natsConnection_,
                                 configuration_.subject.c_str());
    // some other c++ code.
  }
}

The above class uses functions imported from c: natsConnection_Connect, natsConnection_SubscribeSync.

Now I need to write a unit test to cover some other c++ code, I am using gtest, I know how to mock a C++ class, but once I use the C code I don’t know how to start.

how do i write the test? Is there has a best practice?


Solution

  • If you are to test the C++ class, then mock that one and treat it as one unit no matter what it calls internally.

    If you want to test the internals of the C++ class including C function calls, then C functions are commonly mocked by simple #define function-like macros. Example:

    #include <stdio.h>
    
    void function (int x)
    {
      printf("%d\n", x);
    }
    
    #define function(x) function(1)
    
    int main (void)
    {
      function(2); // prints 1
    }