Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an existing class can be unit-tested?

Recently, i took ownership of some c++ code. I am going to maintain this code, and add new features later on. I know many people say that it is usually not worth adding unit-tests to existing code, but i would still like to add some tests which will at least partially cover the code. In particular, i would like to add tests which reproduce bugs which i fixed.

Some of the classes are constructed with some pretty complex state, which can make it more difficult to unit-test.

I am also willing to refactor the code to make it easier to test.

Is there any good article you recommend on guidelines which help to identify classes which are easier to unit-test? Do you have any advice of your own?

like image 253
zr. Avatar asked Jan 25 '11 16:01

zr.


3 Answers

While Martin Fowler's book on refactoring is a treasure trove of information, why not take a look at "Working Effectively with Legacy Code."

Also, if you're going to be dealing with classes where there's a ton of global variables or huge amounts of state transitions I'd put in a lot of integration checks. Separate out as much of the code which interacts with the code you're refactoring to make sure that all expected inputs in the order they are recieved continue to produce the same outputs. This is critical as it's very easy to "fix" a subtle bug that might have been addressed somewhere else.

Take notes too. If you do find that there is a bug which another function/class expects and handles properly you'll want to change both at the same time. That's difficult unless you keep thorough records.

like image 139
wheaties Avatar answered Sep 20 '22 11:09

wheaties


Presumably the code was written for a purpose, and a unit test will check if the purpose is met, i.e. the pre-conditions and post-conditions hold for the methods.

If the public class methods are such that you can externally check the state it can be unit tested easily enough (black-box test). If the class state is invisible or if you have to test tricky private methods, your test class may need to be a friend (white-box test).

A class that is hard to unit test will be one that

  • Has enormous dependencies, i.e. tightly coupled
  • Is intended to work in a high-volume or multi-threaded environment. There you would use a system test rather than a unit test and the actual output may not be totally determinate.
like image 37
CashCow Avatar answered Sep 20 '22 11:09

CashCow


I written a fair number of blog posts about unit testing, non-trivial, C++ code: http://www.lenholgate.com/blog/2004/05/practical-testing.html

I've also written quite a lot about adding tests to existing code: http://www.lenholgate.com/blog/testing/

like image 37
Len Holgate Avatar answered Sep 20 '22 11:09

Len Holgate