I'd like to measure, how well unit-testable is my code. I don't have a concrete idea, how it should look like, but my logic is:

There are a lot of formally checkable and quantifiable criteria for well testable code:

  • usage of global/static functions/variables,
  • cyclomatic complexity,
  • DI vs. wild direct instantiating of classes, where they are used,
  • and many more.

And since the testability of code can be described by quantifiable criteria, it should be possible to quantify the testability itself.

Is there something like a "testability index"? How to quantify/measure the testability of an application?

  • 9
    The easiest way to see if a piece of code is unit-testable is by attempting to write some unit tests against it. The harder that process is, the less unit-testable your code is. – Robert Harvey Apr 25 '17 at 1:14
  • Regardless whether such a measure is possible, it's relationship to "good" or "useful" won't be absolute. – whatsisname Apr 25 '17 at 5:56
  • 3
    If you make every member of a class public, this will significantly increase your component's "unit-testability index". However, it will probably not increase the quality of its design. – Doc Brown Apr 25 '17 at 6:59
  • 1
    Another interesting measure is how important it is to test the code independently (in a unit test). Large quantities of low value tests impede development. Many of the benefits of low-level unit testing can be achieved by dynamically checking invariants and postconditions in all running code, without destroying encapsulation. – Frank Hileman Apr 25 '17 at 15:23
  • 1
    I might come back later with a better answer but I'd say the 'testability' of a piece of code is at least some-what dependent of its pureness (in terms of functional programming). If the piece of code you want to test does a println or console.log instead of return a string, it cannot be tested. If your code has side-effects, it's harder to test those side-effects. It's all about exposing an API where you can assert or expect a certain value. – Rico Kahler Apr 25 '17 at 16:46

No such index exist to my knowledge, and I don't think testability is quantifiable in a meaningful way.

The criteria you mention are indeed quantifiable, but they are not really related to testability.

Static methods or direct instantiation of objects does not prevent you from testing code. It just prevent you from mocking. But the need for mocking is itself a code smell which might indicate a problematic design.

If the code is overall well-designed, cyclomatic complexity just reflects the complexity of the business requirements. So it doesn't really tell you if the code is more or less testable, it just show you how much work you have to do if you want full branch coverage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.