Catch2 icon indicating copy to clipboard operation
Catch2 copied to clipboard

How to Test Private function members in a class.

Open shangxiudong opened this issue 4 years ago • 2 comments

Description I encountered trouble when I was going to test a particular class's private functions. I can‘t call it straightly.

shangxiudong avatar Jul 22 '21 08:07 shangxiudong

Generally it's seen as bad practice to test private methods, it's normally encouraged that you test the public interface only. Some people add a define to make private methods available in a test build such as...

#define private public

However, I wouldn't recommend this unless you really need it.

Another technique (definitely not frowned upon) is to move the private method into a free function that takes additional arguments rather than relying on private implementation details. See this video for more details on this point. To be honest I rarely rely on private methods any more and reserve private for data members only.

Anthony-Nicholls avatar Aug 03 '21 18:08 Anthony-Nicholls

this was already discussed in #258 ,though it was about the philosophy and opportunity of doing private member tests, not the technical mechanism... I don't agree with the conclusions as IMHO a library should not force a point of view in thit regard. In my case I have some private machinery that needs to be tested and I want to do it without changing the architecture of the code; I know the implicitations of testing private stuff, but it's my choice!

tecnoprogram-thomas avatar May 27 '22 10:05 tecnoprogram-thomas