I thought of writing ut for a complex algorithm, which consits of many steps. For example, the algorithm class like below. And I want to test every step. But it's obvious that i can process the private function. I am using the google gtest.
How shall I design the UT?
Class Algorithm
{private:
PreProcess();
Process();
PostProcess();
}
There is a specific section in the Google Test documentation dealing with testing private code.
Short version is, try to avoid testing non-public functions. If you have to, then you can either change your class design, or your test can be made a friend of the class.
GTest provides a helper macro for this last option: FRIEND_TEST
, but beware of namespace issues with this. Your test needs to be defined in the same namespace as the class being tested for this macro to work.
So something like:
#include <iostream>
#include "gtest/gtest.h"
class Algorithm {
private:
bool PreProcess() { std::cout << "Pre\n"; return true; }
bool Process() { std::cout << "Process\n"; return true; }
bool PostProcess() { std::cout << "Post\n"; return true; }
FRIEND_TEST(AlgorithmPrivateTest, PreProcess);
FRIEND_TEST(AlgorithmPrivateTest, Process);
FRIEND_TEST(AlgorithmPrivateTest, PostProcess);
};
class AlgorithmPrivateTest : public testing::Test {
protected:
AlgorithmPrivateTest() : algorithm_() {}
Algorithm algorithm_;
};
TEST_F(AlgorithmPrivateTest, PreProcess) {
EXPECT_TRUE(algorithm_.PreProcess());
}
TEST_F(AlgorithmPrivateTest, Process) {
EXPECT_TRUE(algorithm_.Process());
}
TEST_F(AlgorithmPrivateTest, PostProcess) {
EXPECT_TRUE(algorithm_.PostProcess());
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}