Mocks Aren’t Stubs

4. Juni 2010

p>Bei Unit Tests entsteht häufig in die Situation, dass konkrete Implementierungen einer Klasse gegen Pseudo-Implementierungen ausgetauscht werden sollen, welche bestimmte Teilaspekte abbilden. Je nach Zweck des Pseudo-Objekts kann es hier zu sehr unterschiedlichen Ausprägungen kommen. Deswegen ist es auch falsch, alle diese Pseudo-Objekte als “Mock” zu bezeichnen. Für konkrete Projekte kann man festhalten: Es sollten Namenskonventionen für Test-Objekte eingeführt und auch eingehalten werden…

Auch Martin Fowler hat sich des Themas angenommen und einen nicht mehr ganz neuen, aber sehr lesenswerten Beitrag dazu geschrieben: Mocks Aren’t Stubs.

Hier der wichtigste Teil daraus:

[Use] the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes. The name comes from the notion of a Stunt Double in movies. [Use] four particular kinds of double:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it ’sent‘, or maybe only how many messages it ’sent‘.
  • Mocks are […] objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Of these kinds of doubles, only mocks insist upon behavior verification. The other doubles can, and usually do, use state verification. Mocks actually do behave like other doubles during the exercise phase, as they need to make the SUT [(System Under Test)] believe it’s talking with its real collaborators – but mocks differ in the setup and the verification phases.