简体   繁体   中英

Getters and Setters vs FRIEND_TEST

I know this is not good class design for UT but...

In case there are protected variables that need to be tested, would it be better to just use FRIEND_TEST to get/set these variables on test? Or should I create getters and setters (for each variable!)?

Ex.

class Dog
{
public:
//some methods

protected:
   int age;
   std::string color;
   std::string breed
}

Declaring a FRIEND_TEST will not require much overhead unlike if I will create getters and setters for each == 6 new methods! But what is the more correct solution?

If you need only one class be able to access your protected members, use friends classes. This is an absolute rule in C++.

Adding getters and setters to your class will just add overhead and, in the best case, your compiler will remove it.

If you want more information about friend classes this link will be useful.

  1. FREIND_TEST is not a good solution as you have no real control who gets access to the protected members.
  2. You may define the tested class as an inner class of the tester class. enable this nesting only on test builds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM