I am trying to use GoogleMock to do UnitTest, meanwhile switching to fake as well.
#include <gmock/gmock.h>
#include <iostream>
using ::testing::Matcher;
class Fake {
public:
void test(int, float) {}
};
class MockTest {
public:
MockTest() :
fake(new Fake()) {
}
MOCK_METHOD2(func, void(int, float));
MOCK_METHOD2(func, void(char*, int));
void delegate() {
ON_CALL(*this, func(Matcher<int>(),
Matcher<float>()))
.WillByDefault([this](int val1, float val2) {
fake->test(val1, val2);
});
}
private:
Fake *fake;
};
int main() {
MockTest *test = new MockTest();
test->delegate();
test->func(1, 5.6);
}
I try to hit fake object everytime func(int, float) is called. It compiles well, but met a segfault. The error message of valgrind shows:
[ethan@ethan test]$ valgrind ./gmock_test
==119183== Invalid read of size 8
==119183== at 0x10DD74: MatchAndExplain (gmock-matchers.h:292)
==119183== by 0x10DD74: Matches (gmock-matchers.h:298)
==119183== by 0x10DD74: Matches<std::tuple<testing::Matcher<int>, testing::Matcher<float> >, std::tuple<int, float> > (gmock-matchers.h:908)
==119183== by 0x10DD74: Matches<std::tuple<testing::Matcher<int>, testing::Matcher<float> >, std::tuple<int, float> > (gmock-matchers.h:907)
==119183== by 0x10DD74: TupleMatches<std::tuple<testing::Matcher<int>, testing::Matcher<float> >, std::tuple<int, float> > (gmock-matchers.h:976)
==119183== by 0x10DD74: Matches (gmock-spec-builders.h:340)
==119183== by 0x10DD74: FindOnCallSpec (gmock-spec-builders.h:1497)
==119183== by 0x10DD74: testing::internal::FunctionMockerBase<void (int, float)>::DescribeDefaultActionTo(std::tuple<int, float> const&, std::ostream*) const (gmock-spec-builders.h:1650)
==119183== by 0x10CF94: testing::internal::FunctionMockerBase<void (int, float)>::UntypedDescribeUninterestingCall(void const*, std::ostream*) const (gmock-spec-builders.h:1672)
==119183== by 0x40550F5: testing::internal::UntypedFunctionMockerBase::UntypedInvokeWith(void*) (in /misc/toolchain-builds/d1ce2497ca66f4a55430c86fd8812027a7e8d5ea.x86_64/lib/libgmock.so)
==119183== by 0x10CB3E: InvokeWith (gmock-spec-builders.h:1603)
==119183== by 0x10CB3E: Invoke (gmock-generated-function-mockers.h:121)
==119183== by 0x10CB3E: MockTest::func(int, float) (test.cc:19)
==119183== by 0x10C957: main (test.cc:37)
==119183== Address 0x0 is not stack'd, malloc'd or (recently) free'd
Could someone tell me how to deal with this problem?