简体   繁体   中英

C++14 unit testing (de)allocation of a private member

I have a deactivate() method, which should, amongst other things, deallocate a private member of the class (ultimately a std::vector 's resize(0) + shrink_to_fit() - but that's not important).

How can I go about unit testing that the member was deallocated by the deactivate method, given that the test has no way to access the private member to check it?

I am trying to avoid dependency injection, because the code is performance critical and I am wary of indirections via references/pointers and potential loss of inlining optimisations. But if there is some magic that avoids these disadvantages, I am all for it!

I am not averse to checking raw memory usage, but of course it's non-trivial with members that allocate on the heap (like std::vector ), and I don't know a way to do it.

I have read plenty of posts about testing private members (abusing friend , compile-time conditionally declaring protected / public ), but I'm hoping someone can give a prettier solution to this more restricted case, or a way to do dependency injection without indirection and loss of inlining.

A simple, effective and performant way is to add public const getter functions that return copies of / const references to the private member variable(s) or their properties that you are interested in.

Consider std::vector itself. It is designed to be a very efficient type for accessing elements (as fast as a dynamically allocated array) but it has numerous getter-like functions such as empty() , size() etc. I am 99.999% confident that some of these will not be used by your code (eg get_allocator() ), but I bet you wouldn't dream of rolling your own own vector class just to remove them in the name of "performance".

Bear in mind that unit testing is about testing the interface to your objects, and not that they use specific data-structures to implement their logic. Thus, I would advise exposing the key properties of the vector data member rather than the vector itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM