1

For example:

Production.cpp

int func1()
{
    return 7;        
}

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

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

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

TestProduction.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();
}

From my understanding, when func1() was mocked, there's no way to test the actual function.

Below sample code is just an idea on what I'm trying to do.

Because I have to test many functions that calls many functions inside. Sometimes, I don't care on the actual result of those other function so I mocked it, but when I want to test the behavior of the real function when calling inside a function that I'm testing, I cannot do it since that function is already mocked.

Also I hope I can do this without modifying the production code, only the tests code.

Manie
  • 11
  • 4

2 Answers2

0

No. You mocked using the linker, so, for the whole file context, the real functions do not exist.

Felipe Lavratti
  • 2,887
  • 16
  • 34
0

You may achieve this by using function pointers (or std::function, …) to set the implementation used by productionCode() at runtime.

Pseudocode

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();
}
ollo
  • 24,797
  • 14
  • 106
  • 155