Monday, February 15, 2010
What is "testable" code? How do I know if my code is "testable" or not? There is a lot of talk in agile teams about making sure we have testable code, so what exactly does that mean? I will try to explain here some of the things that make code testable.

TDD Methodology
If we are using test-driven development to write the code, it is inherently testable since the tests drove us to write it. However, it is still possible that over time, refactoring can be done in such a way to make it less so. This is not likely however since all the unit tests would be passing.

Dependencies
If the code requires so many external dependencies that we must essentially spin up large parts of the system to test it, this is a clear red flag for testability. We should be able to mock out dependencies and isolate the code under test. If we can't do that, it's not testable. Our dependency relationships should be reasonable and sensible. If there is a "smell" here it probably means that there's work to do to make it testable.

Internal States
If there are lots of internals and complex states without interfaces to access and manipulate them, this is another red flag that the code's not testable. If there is a lot of internal logic and things that happen based on state, this should all be unit tested. If there's not a unit test for each thing that goes on internally, it's not testable. Here again if code is written using TDD this usually doesn't become a problem.

Setup
If the code requires a large amount of setup code to test it, this again is another red flag. I look at the amount of effort it takes to validate that a class does the one thing it's supposed to do. If the test code is more than the main code, it's probably a sign that it's not very testable. Databases are notorious for this issue. I have some database code that's a good example of this concept. The amount of code and data needed to get the database to the state to exercise the few procedures there greatly exceed the code itself. This is kind of combining both the dependencies and internal state concepts, and I think it's definitely not very testable.

Testability is a goal we strive for, it helps us to be able to make sure the code operates successfully and is maintainable. Write good unit tests. Look for testability in the small, and that will help the overall system to be more testable as well.

Monday, February 15, 2010 8:21:07 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]  | 
© Copyright 2010, John E. Boal