Google Test Expect Call from a Function

Viewed 4352

Say I have a simple test with mocks.

#include "boost/interprocess/detail/interprocess_tester.hpp"
#include <gtest/gtest.h>
#include <gmock/gmock.h>

using namespace ::testing;

struct IInterface
{
    virtual void method(int foo) = 0;
};

struct SimpleMock : public IInterface
{
    MOCK_METHOD1(method, void(int foo));
};

struct TestFixture : public Test
{
    TestFixture()
    {
        // Don't care about other invocations not expected
        EXPECT_CALL(mock, method(_)).Times(AnyNumber());
    }

    void setupExpectation(int data)
    {
        EXPECT_CALL(mock, method(data)).Times(1);
    }

    SimpleMock mock;
};

TEST_F(TestFixture, SimpleTest)
{
    setupExpectation(2);

    mock.method(2);

    setupExpectation(5);

    mock.method(3); // will fail expectation
}

This will fail with the message below referencing into the helper method, which makes it hard to debug or figure which expectation failed since I don't see the line I called setupExpectation or the actual argument value.

test_HarmonicTherapyStateMachineAit.cpp:27: Failure
Actual function call count doesn't match EXPECT_CALL(mock, method(data))...
         Expected: to be called once
           Actual: never called - unsatisfied and active

Note my actual use case has more complicated expect calls where I think it warrants splitting it into a separate method (and having multiple expectations in one test). However, I'm not sure how to get a more informative error message from this.

I've read about http://google.github.io/googletest/gmock_cook_book.html#controlling-how-much-information-gmock-prints. However, this provides more information than I really want, which is just a line number of the function that calls setupExpectation.

I also just tried making a MACRO to wrap the common expectations. This would be easy in this simple case. However, my actual use case has more complicated logic that I'd rather not place into a macro.

Even if I could do something like EXPECT_CALL(...).Times(1) << "argument: " << foo; That would be helpful.

Any help would be appreciated.

1 Answers

Currently I had the same problem, that gmock provides me very few information. My solution was to write a custom Matcher.

The syntax of the EXPECT_CALL macro is according to the documentation:

EXPECT_CALL(mock_object, method(matchers))

A quick solution could be to write a matcher, which in case of an error prints a message to the screen.

e.g:

MATCHER_P2(isEqual, expected, line, "")
{
  bool isEqual = arg == expected;

  if(!isEqual)
    printf("Expected argument: %d, actual: %d (EXPECT_CALL line: %d)\n", expected, arg, line);

  return isEqual;
}

The EXPECT_CALL then changes to

EXPECT_CALL(mock, method(isEqual(3, __LINE__))).Times(1);

Please let me know if you have another/better solution to this.

Related