簡體   English   中英

使用 C 函數時如何測試 C++ 代碼

[英]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.
  }
}

上面的 class 使用從 c 導入的函數: natsConnection_ConnectnatsConnection_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.

我怎么寫測試? 有最佳實踐嗎?

如果我猜對了,您想為 C 函數編寫單元測試。 也許您可以為 C 函數編寫一個包裝器,例如:

return_type natsConnection_Connect_CPP(arg1, arg2, ..., argN)
{
return natsConnection(arg1,arg2,...,argN);
};

然后你可以為你的 function 使用 gtest。 我對 gtest 不熟悉,因為我以前從未使用過它。

如果您要測試 C++ class,那么無論它在內部調用什么,都要模擬它並將其視為一個單元。

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. 例子:

#include <stdio.h>

void function (int x)
{
  printf("%d\n", x);
}

#define function(x) function(1)

int main (void)
{
  function(2); // prints 1
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM