unit-testingc++14googletestgooglemockstdany

How to gtest / gmock function accepting std::experimental::any argument?


Issue

I need a help in fixing my unit test issue with gtest 1.10.0 version. When I tried to unit test involving a function that accepts std::experimental::any argument, exception is thrown and unit test terminated.

Steps to reproduce the issue

Snippet of unit tests covering my test scenario available under https://godbolt.org/z/Y7dvEsaPf In TestBoth testcase, if EXPECT_CALL and actual function calls are adjacently provided, exception is not thrown and test case execute successfully. But in my actual project code, my test function has call to send_data() function with both these data types.

Tool and operating system versions gtest version is 1.10.0 Ubuntu Linux 20.04

Compiler version

g++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0 C++14

Build system

cmake version 3.20.5

Additional context

Help needed or please direct to where I can get this query asked and get resolved.


Solution

  • The issue is that AnyMatcher matches successfully any std::any. The solution is in forcing further expectations with help of ::testing::InSequence:

    TEST(MockUseWith, TestBoth)
    {
        TestMock mock;
    
        InSequence seq;
    
        EXPECT_CALL(mock, send_data(AnyMatcher(EnableReq{true})));
        EXPECT_CALL(mock, send_data(AnyMatcher(ReadReq())));
        mock.send_data(EnableReq{true});
        mock.send_data(ReadReq{});
    }
    

    https://godbolt.org/z/eaj4Pxb1T

    [==========] Running 2 tests from 1 test suite.
    [----------] Global test environment set-up.
    [----------] 2 tests from MockUseWith
    [ RUN      ] MockUseWith.TestBoth
    [       OK ] MockUseWith.TestBoth (0 ms)
    [ RUN      ] MockUseWith.TestOne
    [       OK ] MockUseWith.TestOne (0 ms)
    [----------] 2 tests from MockUseWith (0 ms total)
    
    [----------] Global test environment tear-down
    [==========] 2 tests from 1 test suite ran. (1 ms total)
    [  PASSED  ] 2 tests.