0

I have the following code, I try to mock a C function using google mock:

This is the header file:

A.h

int getValue(int age, int* value, int* number);

This is the source file:

A.c

int getValue(int age, int* value, int* number)
{
    // do something and return value
    return 10;
}

This is source file b.c, which using a.h

b.c

#include <a.h>

void formValue()
{
   int b = 10;
   int c = 20;
   getValue(1, &b, &c);    
}

This is the mock file:

AMock.hh

#include "a.h"

class AFileMock {
  public:
    AFileMock();
    ~AFileMock();
    MOCK_METHOD3(getValue, int(int, int *, int *));
};

Then in the test:

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include <b.h>
#include <AFileMock.h>

using testing::_;
using testing::Return;
using testing::InSequence;

class BTest: public testing::Test {

protected:
   AFileMock aFile;

public:
   void SetUp() { }
   void TearDown() { }
};


TEST_F(BTest, test1)
{
   InSequence sequence;
   EXPECT_CALL(aFile, getValue(_, _, _)).
      Times(1);

   formValue();
}

when I try to run this test, it complains that the get link error in the Mock file, it says:

link error: getValue(_, _, _) is not defined, and it points to the Mock file AMock.hh.

But if I use MOCK_CONST_METHOD instead of MOCK_METHOD in the Mock, it work:

MOCK_CONST_METHOD3(getValue, int(int, int *, int *));

No complier errors.

What is the reason for this?

ratzip
  • 1,571
  • 7
  • 28
  • 53

1 Answers1

1

replace

AMock.hh

#include "a.h"

with

AMock.hh

extern "C" {
    #include "a.h"
}

here is why: In C++ source, what is the effect of extern "C"?

Community
  • 1
  • 1
fukanchik
  • 2,811
  • 24
  • 29