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

后端 未结 6 1856
予麋鹿
予麋鹿 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:24

    I think there needs to be a distinction between future-proofing the class by providing accessors to its users if it makes sense to do so, and improving testability. I'm also not a big fan of befriending classes for the sole purpose of testing as this introduces a tight coupling in a place where I prefer not to have it.

    If the sole use of the accessors is to provide a way for the test cases to check internal state of the class, it normally doesn't make sense to expose them publicly. It also can tie down implementation details that you might wish to change later on but then find you can't because someone else is using said accessors.

    My preferred solution for this would be to provide protected accessor functions to communicate clearly to the class's users that these are not part of the public interface. Your tests would then create a minimal derived class of the original which contains call-through stubs for the parent's functions but also makes the accessors public so you can make use of them in the test cases.

提交回复
热议问题