为什么我的代码中没有调用 g-mocked 方法

Why the g-mocked method is not called in my code

我正在尝试实现一个模拟方法并验证是否只调用了该方法。下面是一个简单的例子,我试图模拟 Class A:ShowPubA2 方法。因此我有以下代码:

class A {
public:
    virtual void ShowPubA1()
    {
        std::cout << "A::PUBLIC::SHOW..1" << std::endl;
    }
    virtual int ShowPubA2(int x)
    {
        std::cout << "A::PUBLIC::SHOW..2 " << x << std::endl;
        return x;
    }
};

class MockA : public A {
public:
    MOCK_METHOD0(ShowPubA1, void());
    MOCK_METHOD1(ShowPubA2, int(int x));
};

现在我声明另一个 class B 继承自 A -

class B : public A
{
public:
    int ShowPubB2(int x)
    {
        ShowPubA2(x);
        std::cout << "B::PUBLIC::SHOW..2 " << x << std::endl;
        return x;
    }
};

以下是我的测试用例详细信息:

TEST(FirstB, TestCall) {
    using ::testing::_;
    MockA a;
    EXPECT_CALL(a, ShowPubA2(_)).Times(AtLeast(1));
    B b;
    EXPECT_EQ(2, b.ShowPubB2(2));
}

从输出中我们可以看到调用了实际实现而不是模拟方法 - 因此测试失败:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Firstb
[ RUN      ] Firstb.TestCall
A::PUBLIC::SHOW..2 2
B::PUBLIC::SHOW..2 2
c:\myuser\documents\c and c++\gmock\consoleapplication1\consoleapplicati
n1\consoleapplication1.cpp(69): error: Actual function call count doesn't match
EXPECT_CALL(a, ShowPubA2(_))...
         Expected: to be called at least once
           Actual: never called - unsatisfied and active
[  FAILED  ] Firstb.TestCall (0 ms)
[----------] 1 test from Firstb (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] Firstb.TestCall

 1 FAILED TEST
Press any key to continue . . .

请告诉我如何模拟一个方法并调用它来代替它的实际方法。

您应该更改 B 以将 A 注入到如下内容:

class B
{
public:
    explicit B(A& a) : a(&a) {}

    int ShowPubB2(int x)
    {
        a->ShowPubA2(x);
        std::cout << "B::PUBLIC::SHOW..2 " << x << std::endl;
        return x;
    }
private:
    A* a;
};

然后

TEST(FirstB, TestCall) {
    using ::testing::_;
    MockA a;
    EXPECT_CALL(a, ShowPubA2(_)).Times(AtLeast(1));
    B b(a);
    EXPECT_EQ(2, b.ShowPubB2(2));
}