Another solution that doesn't require you to add any gtest
headers or macros to your production code could be to mark the private
members as protected
and create a derived class used in your tests with public functions exposing the private members.
Class to be tested:
#include <cstdint>class Widget {protected: uint8_t foo; uint8_t bar; void baz();}
And the test class:
#include "gtest/gtest.h"#include <cstdint>#include "../src/widget.h"// create a "test" class derived from your production classclass TestWidget : public Widget {public: // create public methods that expose the private members uint8_t getFoo() { return foo; } void callBar() { bar(); }}TEST(WidgetTests, TestFoo) { // Use the derived class in your tests TestWidget widget; // call a protected method widget.callBar(); // check the value of a protected member EXPECT_EQ(widget.getFoo(), 10);}
Of course the main caveat here is that you must mark the private
members you need to access as protected
, but it's another option if you want to keep the "test" code out of your production classes.