What is wrong with making a unit test a friend of

2019-01-16 10:43发布

In C++, I have often made a unit test class a friend of the class I am testing. I do this because I sometimes feel the need to write a unit test for a private method, or maybe I want access to some private member so I can more easily setup the state of the object so I can test it. To me this helps preserve encapsulation and abstraction because I am not modifying the public or protected interface of the class.

If I buy a third party library, I wouldn't want its public interface to be polluted with a bunch of public methods I don't need to know about simply because the vendor wanted to unit test!

Nor do I want have to worry about a bunch of protected members that I don't need to know about if I am inheriting from a class.

That is why I say it preserves abstraction and encapsulation.

At my new job they frown against using friend classes even for unit tests. They say because the class should not "know" anything about the tests and that you do not want tight coupling of the class and its test.

Can someone please explain these reasons to me more so that I may understand better? I just do not see why using a friend for unit tests is bad.

7条回答
Bombasti
2楼-- · 2019-01-16 11:45

Typically you only test the public interface so that you are free to redesign and refactor the implementation. Adding test cases for private members defines a requirement and restriction on the implementation of your class.

查看更多
登录 后发表回答