如何为以下适配器类(继承类)编写 GTest。继承类的 MockObject 未按预期工作

问题描述 投票:0回答:0
class BAdapter : public A, public C
{
public:
    BAdapter(){ 
        auto boundACallback = std::bind(&BAdapter::service_state_A, this, std::placeholders::_1);
        auto boundCCallback = std::bind(&BAdapter::service_state_C, this, std::placeholders::_1);

        A::init_A(boundACallback);
        C::init_C(boundCCallback);
    }
};

//TESTING using GTest Framework

class MockAC : public A, public C
{
public:
    MOCK_METHOD1(init_A, void(TServerStateCallback&));
    MOCK_METHOD1(init_C, void(TServerStateCallback&));
};

TEST_F(BAdapterTest, ConstructorTest) {
    // Set up expectations for the mock object
    TServerStateCallback expectedACallback = [](ESTATE const& state) {};
    EXPECT_CALL(*mockAC, init_A(_))
        .WillOnce(Invoke([&](TServerStateCallback& callback) {
            // Call the callback function with a valid state
            callback(ESTATE::AVAILABLE);
        }));

    TServerStateCallback expectedCCallback = [](ESTATE const& state) {};
    EXPECT_CALL(*mockAC, init_C(_))
        .WillOnce(Invoke([&](TServerStateCallback& callback) {
            // Call the callback function with a valid state
            callback(ESTATE::AVAILABLE);
        }));

    // Create an object of class B
    BAdapter b;

    // Verify that the expectations were met
    Mock::VerifyAndClearExpectations(mockAC.get());
}

尽管预期设置正确,但类 B 的构造函数中对 A::init_A 和 C::init_C 的调用似乎没有被模拟对象 (mockAC) 拦截。这些导致以下测试失败。

任何专家建议如何从 GTest 框架中涵盖这种情况?

Actual function call count doesn't match EXPECT_CALL(*mockAC, init_A(_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
Actual function call count doesn't match EXPECT_CALL(*mockAC, init_C(_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
[  FAILED  ] BAdapterTest.ConstructorTest (0 ms)
c++ googletest
© www.soinside.com 2019 - 2024. All rights reserved.