CUNIT-「モッキング」LIBC関数
-
26-10-2019 - |
質問
プロジェクト単位テストにはCUNITを使用しています。適切なパラメーターを使用してLIBC関数を呼び出すかどうか、およびそれらの返品値を正しい方法で扱うかどうかをテストする必要があります。たとえば、バインド(...)関数を呼び出す場合 - これが間違っている場合はどのAFパラメーションとアサートを確認したいと思います。正しい方法。
これらの目的のために、Cunit環境には、テスト中に「mocked」bind()関数を呼び出し、コードを実行するときに実際のbind()関数を呼び出すための組み込みメカニズムがあることを期待しますが、これ。
Cunitで何かが足りないのか、それともこれを実装する方法を提案してください。
ありがとう、ジョー。
解決
残念ながら、CunitでCの関数を模倣することはできません。
ただし、定義を使用して虐待することにより、独自の模擬関数を実装できます。テスト用にコンパイル時に不定を定義すると仮定すると、テストされたファイル(または含まれる)で次のようなものを定義できます。
#ifdef UNITTEST
#define bind mock_bind
#endif
テストモードでコンパイルするmock_helper.cファイルで:
static int mock_bind_return; // maybe a more complete struct would be usefull here
static int mock_bind_sockfd;
int mock_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
CU_ASSERT_EQUAL(sockfd, mock_bind_sockfd);
return mock_bind_return;
}
次に、テストファイルで:
extern int mock_bind_return;
extern int mock_bind_sockfd;
void test_function_with_bind(void)
{
mock_bind_return = 0;
mock_bind_sockfd = 5;
function_using_bind(mock_bind_sockfd);
}
他のヒント
glibcmock Mocking libc関数の解決策です Googleテスト. 。例えば:
#include "got_hook.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <sys/socket.h>
#include <mutex>
#include <memory>
struct MockBind {
MOCK_METHOD3(Bind, int(int, const struct sockaddr*, socklen_t));
};
static MockBind *g_mock{nullptr};
static int Bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
return g_mock->Bind(sockfd, addr, addrlen);
}
static std::mutex g_test_mutex;
TEST(BindTest, MockSample) {
std::lock_guard<std::mutex> lock(g_test_mutex);
std::unique_ptr<MockBind> mock(g_mock = new MockBind());
testing::GotHook got_hook;
ASSERT_NO_FATAL_FAILURE(got_hook.MockFunction("bind", (void*)&Bind));
// ... do your test here, for example:
struct sockaddr* addr = nullptr;
EXPECT_CALL(*g_mock, Bind(1, addr, 20)).WillOnce(testing::Return(0));
EXPECT_EQ(0, bind(1, addr, 20));
}
所属していません StackOverflow