Commenti al post “Don’t Over-Use Mock Objects” di K.Ray

Tempo fa Giuliano aveva segnalato questo post di K.Ray: Don’t Over-Use Mock Objects

Mi sembra che le tesi dell’articolo siano un po’ forti (“Avoid them. Mocks make your tests more fragile and more tightly-coupled. And at the same time, they reduce the integration-test aspects of TDD. They make your tests larger and more complicated and less readable.”). Certo, se usati male possono dare problemi di fragilita’ eccessiva del test e di leggibilita’ (a meno che non si usi un po’ di literate programming con jMock), e soprattutto se non si usano per riflettere su eventuali debolezze del proprio codice (a questo riguardo il blog su www.mockobjects.com fa spesso illuminanti esempi di codice che usa scorrettamente i mock).

L’obiezione che i mock ridurrebbero la robustezza dei test e’ debole (“If you change an object’s API, a mock object’s API may not change, making your tests out-of-date with respect to your non-test code”), perche’ con EasyMock si usano le API ‘vere’, pertanto non esite la possibilita’ di avere dei metodi ‘out of date’ (non so come funzioni invece jMock).

L’unica osservazione secondo me con un certo fondamento e’ la critica al modo di procedere degli interaction-based testers (“In TDD, you normally write a test, write some code in a target class/method that passes the test. The third step is refactoring. … Test-Driving with Mocks inverts that order: you create your target class and a mock class up-front, and plan on how they interact, instead of evolving that interaction in TDD’s refactoring steps. You pre-judge the class design rather than evolve it.”). Anche a me suona innaturale di norma procedere come gli interaction-based testers, ma penso anche che ci siano casi in cui questa ‘esplorazione’ delle interazioni e’ utile.
Suonera’ un po’ eccessivo, ma qualcuno diceva che la programmazione dei mock in un test e’ un po’ come un sequence diagram sotto forma di codice! :-)

Siamo invece d’accordo che i mock sono utili per rendere piu’ indipendenti i test (“Mocks are tool for decoupling, and I do sometimes use them. I limit my use of Mocks to those situations where the real object will not reliably do what I want. Examples: simulating errors in writing a file; simulating connections with a remote server; simulating errors from remote server.”).

2 thoughts on “Commenti al post “Don’t Over-Use Mock Objects” di K.Ray

Leave a comment