I’m working on a C++ production code here with googletest/googlemock. I’ve stumble upon this idea when working with one of the function in A.cpp:
bool A::process_(false);
bool A::process()
{
if ( !process_ ){
process_ = true;
}
return process_;
}
where the header contains:
protected:
static bool process_;
public:
static bool process();
I am stuck in a way that I can only test the function for an expected output of true or an input of false like so:
TEST(ATest, processVal){
A a;
EXPECT_TRUE(a.process());
}
Is there a way to test the function so that both *true* and *false* value of process_ is passed ? So that the test covers the decision for both.
I was thinking mocking so that it can expect a call for both true and false but because it is not a function in a member of a class, I guess you can not do mocking for process_ ?
If you can, how to mock the variable?
Note: I’m on linux and gcc 🙂 thank you !
Advertisement
Answer
- Solution1: To access any
protectedattribute/method from a test without modifying production code
You can easily modify _process even if protected, just do this:
class SubA : public A
{
public:
void setProcess( bool val ) { process_ = val; }
};
A a;
SubA* pA = (SubA*) &a;
pA->setProcess( false );
This will work pretty well and is safe. Even if you are casting A* to SubA* which is not really valid, it will work as SubA objects in memory are the same as A objects (as SubA does not declare any extra attribute).
This only works because process_ is protected, so you create a derived class SubA and use it because compiler will allow this subclass to access the protected stuff.
- Solution2: To access any
protectedand evenprivateattribute/method from a test without modifying production code
Now, if process_ was private, this would not work…but, private/protected is only managed by the compiler…the attributes are here in memory and you may access them even if you are not “allowed to”.
It’s ugly but works perfectly:
#define protected public
#define private public
#include "A.h"
#undef private
#undef protected
{
A a;
a._process = false;
}
This hack makes it easy to access any private/protected attributes/functions from your test programs.