Using a friend class vs. adding accessors for unit testing in C++?

后端 未结 6 1776
予麋鹿
予麋鹿 2021-02-08 03:50

Is it better to add functions that return the internal state of an object for unit testing, as opposed to making the testing class a friend? - especially, when there is no use f

6条回答
  •  醉话见心
    2021-02-08 04:33

    Using friend classes for unit testing is a perfectly legitimate and allows you to maintain encapsulation. You should not modify your classes public interface simply to make the class more testable. Think about it this way. What if you purchased a third party FTP library and you are trying to use it and it's public interface is cluttered with a bunch of methods you don't even need to know about simply because of unit tests! Even modifying a protected interface to compensate for unit tests is BAD. If I am inheriting from some class, I don't want to have to worry about what methods are useful to me and which ones are only there because of unit tests!!! Using friends classes for unit tests helps you maintain a simple, easier to use class interface; it helps to preserve encapsulation and abstraction!!!

    I have heard the argument that using friend classes for unit testing is bad because the class under test should not be "tightly coupled" with its test class and it should not "know" anything about its test class. I do not buy this. It's a single line added to the top of the class:

    friend class MyClassTest;

    and now you can test your class any way you want!

    Now I do agree that you should not use a friend class unless it is necessary. If you can test what needs testing without making it a friend, by all means do. But if life gets difficult and using a friend class makes life easy again, use it!

提交回复
热议问题