-
Notifications
You must be signed in to change notification settings - Fork 10.6k
Description
Does the feature exist in the most recent commit?
No.
Why do we need this feature?
To be able to use the googlemock framework safely without invoking undefined behavior.
Describe the proposal.
The documentation says:
"Important note: gMock requires expectations to be set before the mock functions are called, otherwise the behavior is undefined"
In practice, this undefined behavior is impossible to prevent. Programmers, code reviewers and static analysis tools cannot detect this reliably in the real world. There is no automated tooling that can catch these issues (unlike most C++ undefined behavior). This makes the googlemock framework a dangerous tool to use.
Consider this example:
// sut.h
class SUT {
public:
SUT(Dependency& dep);
void run();
private:
Dependency& dep_;
};
// sut.cpp
SUT::SUT(Dependency& dep) : dep_{dep} {
dep_.init(); // UB: init() called prior to EXPECT_CALL
}
void SUT::run() { dep_.run(); }
// sut_test.cpp
class SUTTest : public ::testing::Test {
protected:
::testing::NiceMock<DependencyMock> dep{};
SUT sut{dep};
};
TEST_F(SUTTest, Test) {
EXPECT_CALL(dep, run()); // UB: EXPECT_CALL after calling init()
sut.run();
}
Code-reviewing the test only, it's impossible for a code reviewer to see that SUT
is calling dep.init()
in its constructor. It's also not possible for static analysis tools to catch this either, because they typically operate on one TU at a time, and here they would need to look at both sut.cpp
and sut_test.cpp
, with control/data flow analysis.
On the other hand, the googlemock framework contains all the information needed to solve this problem. It keeps tracks of exactly which functions have been called on the mock, how many times, etc.
Therefore, googlemock should throw an error if it encounters an instance of EXPECT_CALL/ON_CALL on a mock object that already has had its functions called.
This pattern is not new. There are similar restrictions on other APIs, e.g. "this function may be called only once", and googlemock fails hard when that restriction is violated.
Is the feature specific to an operating system, compiler, or build system version?
No.