Programmer
Programmer

Reputation: 8717

Test Cases states Failed but value returned is true

I have written up a simple sample code to understand GMOCK used for unit testing:

#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;
class A {
public:
    void ShowPub1()
    {
        std::cout << "A::PUBLIC::SHOW..1" << std::endl;
    }
    int ShowPub2(int x)
    {
        std::cout << "A::PUBLIC::SHOW..2" << std::endl;
        return true;
    }
};

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

Below is my test code - I just wish to call ShowPub2 method of class A. I was expecting the statement A::PUBLIC::SHOW..2 to get printed at console - but it just did not happen and the test case also failed though the method is hardcoded to return true:

TEST(FirstA, TestCall) {
    MockA a; 
    EXPECT_CALL(a, ShowPub2(2)) 
        .Times(AtLeast(1));
    a.ShowPub2(2);
    EXPECT_TRUE(a.ShowPub2(2));
}

GMOCK test code execution output - I am not sure why the output A::PUBLIC::SHOW..2 did not rendered in console and test case failed:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from FirstA
[ RUN      ] FirstA.TestCall
c:\users\user1\documents\c and c++\gmock\gmock1\gmock1\gmock1.cpp(78): error:
Value of: a.ShowPub2(2)
  Actual: false
Expected: true
[  FAILED  ] FirstA.TestCall (0 ms)
[----------] 1 test from FirstA (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  ] FirstA.TestCall

 1 FAILED TEST
Press any key to continue . . .



int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
    return 0;
}

Upvotes: 0

Views: 75

Answers (1)

Daksh Gupta
Daksh Gupta

Reputation: 7814

Some clarification is needed here..

Creating a Mock class means that the Mock methods are generate with its own implementations. These line of code

MOCK_METHOD0(ShowPub1, void());
MOCK_METHOD1(ShowPub2, int(int x));

doesn't mean it will call parent implementation of ShowPub1 / ShowOub2. This only means that you'll get a function (Mock) with same signature as that of the class you're mocking.

The test fails because of this line

EXPECT_TRUE(a.ShowPub2(2));

Since the original implementation is not called, this function fails.

The test function should be written as

TEST(FirstA, TestCall) {
    MockA a;
    EXPECT_CALL(a, ShowPub2(2)) .Times(AtLeast(1));
    a.ShowPub2(2);
  }

Here you're testing the behavior that the function is called at least once and the test will be successful with that.

If you want to test the functionality of a function, write separate tests. Mocking will not solve the problem in this case.

Upvotes: 1

Related Questions