我们如何才能将 NiceMock<> 行为应用于单个方法?

How can we get NiceMock<> behavior to apply to a single method?

当在没有期望集的情况下调用模拟方法时,gmock 会发出警告:

GMOCK WARNING:
Uninteresting mock function call - returning default value.
    Function call: getAddress(@0x563e6bbf5530 16-byte object <F0-3A 32-6B 3E-56 00-00 30-A7 BF-6B 3E-56 00-00>)
          Returns: ""
NOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.

可以通过在注入之前用 NiceMock<> 包装模拟来抑制此类警告。是否有可能获得相同的效果,但仅限于 mock 上的某些方法?

例如,考虑这个模拟(使用旧版本的 gtest 编写):

class PocoMock : public Poco
{
public:
    PocoMock() //
        : Poco()
    {
    }

    MOCK_CONST_METHOD1(listen, void(Poco::Net::ServerSocket& rSocket));
    MOCK_CONST_METHOD1(start, void(Poco::Net::TCPServer& rServer));
    MOCK_CONST_METHOD1(stop, void(Poco::Net::TCPServer& rServer));

    MOCK_CONST_METHOD1(
            getAddress,
            std::string(const Poco::Net::StreamSocket& rSocket));
}

是否可以告诉 gmock 抑制关于 getAddress() 的意外调用的警告,而不是关于 listen()start()stop() 的警告?

您可以明确表示您可以拨打任意数量的 getAddress:

EXPECT_CALL(mock, getAddress(testing::_)).Times(testing::AnyNumber());

Demo