I'm using gtest as my unit test framework. In my work, it's a common case that a public method modifies some private variables in the object. These variables stores the "states" of the object and has affects to the object's behavior. For example:
class ConferenceRoom {
public:
void AddUser(const std::string& user_info);
void OnDataReceived(uint32_t user_id, const std::string& message);
private:
// Map[user_id] --> User
std::unordered_map<uint32_t, User> user_map_;
};
I want to test the public method AddUser
with various good/bad user_info, but I can't access the private variable user_map_
directly to check if this map is changed as I expected. I don't know what's the best practice for this case? I know some solutions:
- Using
friend
to access ConferenceRoom's private variable, this will make ConferenceRoom aware test code. - Declare
user_map_
as protected, and using TestRoom inherits ConferenceRoom, then check the map in TestRoom. - Add a virtual private method
const std::unordered_map<uint32_t, User>& GetUserMap() const
; using TestRoom inherits ConferenceRoom and overrides this virtual method, then access privateuser_map_
withGetUserMap
.
I'm sure there must be some other solutions for this case. In my mind, the solution should be isolate class ConferenceRoom
with test code, and the class ConferenceRoom can be delivered to use clearly without any strange code. What your best practice?