Michael Feathers on testing private methods

2008 Febbraio 8

Da un articolo di InfoQ, la posizione di M.Feathers sul testare i metodi privati:

Michael Feathers suggested last year in The Deep Synergy Between Testability and Good Design that TDD encourages good design and, conversely, code that is not testable should make us think twice:

When I write tests and I have the urge to test a private method, I take it as a hint. The hint tells me that my class is encapsulating so much that it has ceased to be “understandable” by tests through its public interface. I listen to the hint, and factor my design differently. Usually, I end up moving the private method (and possibly some methods around it) to a new class where it can be non-private and accessible to tests.

Condivido al 100%!

E interessante anche quello che dice dopo, nel post originale, riguardo alla relazione tra coupling, cohesion e testabilita’.

In the end, it all comes down to cohesion and coupling.  If classes are deeply coupled with their neighbors, it is hard to control them in a test or observe them independently.  If a class isn’t cohesive, it may have some logic which is not easily exercisable through its public interface.

It seems that reverse is true also.  Classes which are hard to instantiate and use in a test harness are more coupled than they could be, and classes with private methods that you feel the urge to test, invariably have some sort of cohesion problem: they have more than one responsibility.

Una Risposta leave one →
  1. 2008 Giugno 1

    In my experience, you really want to test private methods only when the public ones became so complex that you refactor them in several smaller private ones.
    And you could start wishing to test them too.

    In these cases usually I smell too many responsabilities. Creating one or two new classes (instead of new private methods) usually helps.

Lascia un commento

Note: You can use basic XHTML in your comments. Your email address will never be published.

Abbonati ai feed di questi commenti tramite RSS