Mock Objects

Torsten Bergmann astares at gmx.de
Tue Jun 27 16:54:59 UTC 2006


Hi Stef,

the MockObject class from Chad is just a simplified version of the Teachable
package I wrote about before. Teachable is able to handle more cases.

see http://astares.blogspot.com/2005/04/teaching-behavior.html

Since Teachable does not implement #initialize (like it is the case in Chads MockObject class) you 
are also able to teach the mock how to behave when an initialize method is sent 
to it.

Just download the package using SM and have a look at the provided test case.
Teachable is also more intention revealing. Instead of just working 
with blocks you can write Chads example with Teachable as:

cart := Cart new.
item := Teachable new.
item whenSend: #total return: 2.99.
cart add: item
...


But as I warned in the previous email: creating dynamic mock objects
(using either Chads code or the Teachable package) is sometimes dangerous.

Think of testing persistence layer code in an application. If you want to get
the tests running without having an actual database connection you can mock it.
You can either either teach an object dynamically how to behave like the real 
DB connection class or implement the mock also as a class with the same signature. 

In such a case I would prefer to implement a real mock class since it can become
a nightmare to debug the code with the #doesNotUnderstand: trick (especially when it 
uses blocks). It is also hard if you refactor the mocked code - this always means
to refactor the mock object in a similar way.

The more behavior/logic to mock the better it is to implement a special mock class
with a similar interface. We just need better tools.

Smalltalk with it's dynamic nature is very powerful - especially for testing. Think of
a general mock framework where mocks can dynamically created from the "mocked object"
or where one can use SUnit to even test the mock: 

       "self assert: (aMockObject behavesLike: mockedObject)".


Bye
Torsten

-- 


"Feel free" – 10 GB Mailbox, 100 FreeSMS/Monat ...
Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail



More information about the Squeak-dev mailing list