XPlayer

A blog on my daily efforts to be a better developer, and keep improving every day.

Perche' Non Si Dovrebbero Mockizzare Classi Concrete

| Comments

Mi sono sempre chiesto perche’ mai Steve Freeman e gli altri ‘padri’ dei Mock Objects e dello stile di testing interaction-based sconsigliassero di fare mock di classi concrete, tanto che jMock ed EasyMock non supportavano questa possibilita’ ‘nativamente’, ma si doveva installare un’estensione a parte, che usa la famosa libreria CGLIB (per inciso con il nuovo jMock 2 e’ possibile fare mock di classi concrete, ma si deve usare la classe UnsafeHackConcreteClassImposteriser, ed il nome dice tutto di come scoraggino questa pratica). Tanto che tempo fa avevo anche commentato un post di Freeman chiedendogli perche’ lui giudicasse il mock di classi concrete come una sorta di ultima possibilita’ da adottare solo in casi di emergenza (es quando si affronta codice legacy particolarmente ostico e chiuso). E lui mi aveva risposto cosi’:
Because then the interface is implicit, which means you can’t see it and you haven’t given it a name. Instead of using the test to expose a feature of the design, you have more to think about whenever you’re working in that area: is the method overwritten? is it in a super class? what about the state of the rest of the class I’m extending? That sort of thing. For me, the CGLIB should have a “Break Glass in Case of Emergency” written on the front. It’s useful in tight situations, but not to be recommended.
Eppero’ nonostante la sua risposta la cosa non mi era ancora chiara fino in fondo. Poi un recente post su mockobjects.com (Test Smell: Mocking concrete classes) mi ha finalmente aiutato a capire meglio le cose. Il fatto e’ che lo scopo del TDD con i Mock Objects e’ quello di scoprire e far emergere relazioni tra oggetti, e dare nomi a queste relazioni. Se pero’ si mantiene la relazione tra oggetti a livello di classi concrete, queste relazioni rimangono per cosi’ dire piu’ nascoste, implicite, e quindi diventa difficile individuarle e darle un nome. Cito direttamente il post, laddove spiega cosa non va con i mock di classi concrete:
The problem with this approach is that it leaves the relationship between the objects implicit. I hope we’ve made clear by now that the intention of Test-Driven Development with Mock Objects is to discover relationships between objects. If I subclass, there’s nothing in the domain code to make such a relationship visible, just methods on an object. This makes it harder to see if the service that supports this relationship might be relevant elsewhere and I’ll have to do the analysis again next time I work with the class.
Addirittura si spinge a dire che lasciando le relazioni tra oggetti a livello di classi concrete, si rischia di violare l’Interface Segregation Principle, perche’ le classi dipendono da una interfaccia piu’ grande di quella che usano veramente. E poi poco piu’ avanti spiega che l’approccio mockist aiuta anche a dare nomi alle relazioni ed ai ruoli, e a ragionare piu’ in termini di dominio piuttosto che di implementazione:
There’s a more subtle but powerful reason for not mocking concrete classes. As part of the TDD with Mocks process, I have to think up names for the relationships I discover—in this example the ScheduledDevice. I find that this makes me think harder about the domain and teases out concepts that I might otherwise miss. Once something has a name, I can talk about it.
Il tutto e’ poi riassunto bene nell’altro post, What the tests will tell you, da leggere e rileggere, dove elenca alcuni benefici derivanti dall’approccio TDD+MockObjects
  • Keeping knowledge local
  • If it’s explicit I can name it
  • More names mean more domain information
  • Pass behaviour rather than data
Detto questo, ammetto che sono sempre stato affascinato da questo approccio ma non ho mai trovato la forza necessaria per decidere di applicarlo un po’ piu’ sistematicamente, metterlo alla prova insomma. Un po’ perche’ nel mio team da sempre si usa l’approccio classico, e l’approccio interaction-based e’ visto con qualche dubbio/sospetto, un po’ perche’ i nostri progetti per ora sono tutti Java 1.4 e quindi buona parte delle comodita’ delle versioni piu’ recenti dei framework jMock e Easymock te le perdi (soprattutto la loro maggiore letteralita’, cosa importante per avere dei test validi).