为什么当EXPECT_CALL没有时,ON_CALL会产生异常?

时间:2014-11-28 15:21:58

标签: c++ windows gmock

我有一段遗留代码,我正在尝试使用模拟进行测试。我想在CheatSheetCookBook中使用ON_CALL或DefaultValue而不是EXPECT_CALL。但是,这两个都抛出异常,而EXPECT_CALL则没有。这或多或少是代码的样子:

class A
{
public:
    virtual B* GetB() { return m_b; }
private:
    B* m_b;
};

class B
{
public:
    virtual C* GetC() { return m_c; }
private:
    C* m_c;
};

class C
{
public:
    virtual void doSomething()
    {
        std::cout << "I just did something.\n";
    }
};

class D
{
public:
    Foo(A* a)
    {
        C* c = a->GetB()->GetC(); // statement causing exception under test
        c->doSomething();
    }
};

所以我嘲笑了A,B和C,在测试中我有类似的东西:

#include <gtest/gtest.h>
#include <gmock/gmock.h>

using ::testing::Return;

class MockA : public A
{
public:
    MOCK_METHOD0(GetB, MockB*());
};

class MockB : public B
{
public:
    MOCK_METHOD0(GetC, MockC*());
};

class MockC : public C
{
public:
    MOCK_METHOD0(doSomething, void());
};

class TestD : public ::testing::Test
{
public:
    TestD()
    {
        EXPECT_CALL(aMock, GetB()).WillRepeatedly(Return(&bMock));
        EXPECT_CALL(bMock, GetC()).WillRepeatedly(Return(&cMock));

        // Throws exception in doSomething()
        //ON_CALL(aMock, GetB()).WillByDefault(Return(&bMock));
        //ON_CALL(bMock, GetC()).WillByDefault(Return(&cMock));

        // Throws exception in doSomething()
        //::testing::DefaultValue<B*>::Set(&bMock);
        //::testing::DefaultValue<C*>::Set(&cMock);
    }

    NiceMock<MockA> aMock;
    NiceMock<MockB> bMock;
    MockC cMock;
};

TEST_F(TestD, FooDoSomething)
{
    D d;
    EXPECT_CALL(cMock, doSomething()).Times(1);
    d.Foo(&aMock);
}

现在我尝试了调试,但在输入模拟方法时会变得粗略。我注意到的一件事是函数都返回非空指针,我认为这是好的。我只是不明白为什么会抛出异常,但更重要的是,为什么EXPECT_CALL行为与ON_CALL或DefaultValue不同。从我可以围绕intertubes收集的内容来看,除了EXPECT之外应该没有任何区别会使“无趣的召唤”警告变得沉默。

抛出的异常是SEH:

1>[----------] 1 test from TestD
1>[ RUN      ] TestD.FooDoSomething
1>Stack trace:
1>unknown file: error: SEH exception with code 0xc0000005 thrown in the test body.
1>[  FAILED  ] TestD.FooDoSomething (1 ms)
1>[----------] 1 test from TestD (1 ms total)

0 个答案:

没有答案