1

问题

我需要帮助来解决我的 gtest 1.10.0 版本的单元测试问题。当我尝试对涉及接受 std::experimental::any 参数的函数进行单元测试时,会引发异常并终止单元测试。

重现问题的步骤

覆盖我的测试场景的单元测试片段可在https://godbolt.org/z/Y7dvEsaPf 在 TestBoth 测试用例中,如果相邻提供 EXPECT_CALL 和实际函数调用,则不会引发异常并且测试用例执行成功。但是在我的实际项目代码中,我的测试函数调用了具有这两种数据类型的 send_data() 函数。

工具和操作系统版本 gtest 版本为 1.10.0 Ubuntu Linux 20.04

编译器版本

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

构建系统

cmake 版本 3.20.5

附加上下文

需要帮助或请直接到我可以询问此查询并得到解决的地方。

4

1 回答 1

2

问题是AnyMatcher成功匹配 any std::any。解决方案是通过以下方式强制实现进一步的期望::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.
于 2022-02-15T02:53:02.647 回答