1

例如:

生产.cpp

int func1()
{
    return 7;        
}

void func2()
{
    printf("func2");
}

void productionCode()
{
    int x = func1();

    if(x==7) func2(); 
}

测试生产.cpp

int func1()
{
    return mock().actualCall("func1").
        returnIntValue();
}

void setExpFunc1(int x)
{
    mock().expectOneCall("func1")
        andReturnValue(x);
}

TEST(testGroupSample, testMockFunc1)
{
    setExpFunc1(8);
    // this will call mock func1()
    productionCode();
}

TEST(testGroupSample, testRealFunc2)
{
    // this will call real func1()
    productionCode();
}

据我了解,当 func1() 被嘲笑时,无法测试实际功能。

下面的示例代码只是我想要做的一个想法。

因为我必须测试许多调用内部许多函数的函数。有时,我不在乎那些其他函数的实际结果,所以我嘲笑它,但是当我想在我正在测试的函数内部调用时测试真实函数的行为时,我不能这样做,因为那个函数已经被嘲笑了。

另外我希望我可以在不修改生产代码的情况下做到这一点,只修改测试代码。

4

2 回答 2

0

不。您使用链接器进行了模拟,因此,对于整个文件上下文,真正的函数不存在。

于 2016-10-28T17:05:19.523 回答
0

您可以通过使用函数指针(或std::function...)来设置productionCode() 运行时使用的实现来实现这一点。

伪代码

int func1() { /* Production }
int func1_mock() { /* Mock */ }


std::function<int()> impl; // Use a function ptr for C 

void productionCode()
{
    int x = impl(); // Call current implementation
    // ...
}

TEST(...)
{
    impl = func1; // Use production code
    productionCode();

    impl = func1_mock; // Use mock instead
    productionCode();
}
于 2016-11-12T15:28:28.403 回答