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

时间:2017-07-31 08:50:48

标签: c++ gmock

我正在尝试实现一个模拟方法并验证只调用它。下面是一个简单的例子,我试图模拟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));
};

现在我宣布继承自A -

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

以下是我的TEST案例详情:

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 . . .

请让我知道如何模拟一种方法并取而代之的是实际的。

1 个答案:

答案 0 :(得分:1)

您应该将{ test: /\.(ttf|eot|woff|woff2)$/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]', publicPath: '/' }, }, { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'file-loader', options: { name: 'img/[name].[ext]', publicPath: '/' }, }, 更改为注入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;
};