Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should non-public functions be unit tested and how?

I am writing unit tests for some of my code and have run into a case where I have an object with a small exposed interface but complex internal structures as each exposed method runs through a large number of internal functions including dependancies on the object's state. This makes the methods on the external interface quite difficult to unit test.

My initial question is should I be aiming to unit test these internal functions as well, as they are simpler and hence easier to write tests for? My gut feeling says yes, which leads to the follow-up question of if so, how would I go about doing this in C++?

The options I've come up with are to change these internal functions from private to protected and use either a friend class or inheritence to access these internal functions. Is this the best/only method of doing this will preserving some of the semantics of keeping the internal methods hidden?

like image 201
dlanod Avatar asked Feb 12 '09 03:02

dlanod


2 Answers

If your object is performing highly complex operations that are extremely hard to test through the limited public interface, an option is to factor out some of that complex logic into utility classes that encapsulate specific tasks. You can then unit test those classes individually. It's always a good idea to organize your code into easily digestible chunks.

like image 104
Ates Goral Avatar answered Sep 30 '22 04:09

Ates Goral


Short answer: yes.

As to how, I caught a passing reference on SO a few days ago:

#define private public

in the unit testing code evaluated before the relevant headers are read...
Likewise for protected.

Very cool idea.


Slightly longer answer: Test if the code is not obviously correct. Which means essentially any code that does something non-trivial.


On consideration, I am wondering about this. You won't be able to link against the same object file that you use in the production build. Now, unit testing is a bit of an artificial environment, so perhaps this is not a deal-breaker. Can anyone shed some light on the pros and cons of this trick?

like image 43
dmckee --- ex-moderator kitten Avatar answered Sep 30 '22 04:09

dmckee --- ex-moderator kitten