[TIP] Mock objects in testing object composition?

Julius Lucks lucks at FAS.HARVARD.EDU
Tue Apr 24 12:57:49 PDT 2007


Hi All,

I am writing a python Grid class, which is composed of several  
objects of class Tile.  A simple example of this is

class Tile(object):
     def __init__(self,x=0,y=0,width=1,height=1):
         """ Initialize tile position """
         self.x = x
         self.y = y
         self.width = width
         self.height = height
         self.area = width*height

     def get_area(self):
         return self.area

class Grid(object):
     def __init__(self,dimensions):
         """Initialize the size of the grid and add tiles."""
         self.dimensions = dimensions
         num_x,num_y,width,height = self.dimensions
         self.tiles = [Tile(x,y,width,height) for x in range(num_x)  
for y in range(num_y)]

     def get_area(self):
         area = 0
         for t in self.tiles:
             area += t.get_area()
         return area

so that a Grid object owns several Tile objects, and that methods of  
the Grid object internally require methods of the tile objects.

My question is how to test this system.  I can write independent unit  
tests for the Tile class no problem since it is isolated itself.   
However, how do I test the Grid behavior, independently of a properly- 
functioning Tile class (i.e. how do I isolate the tests of the Grid  
object)?  Do I use mock Tile objects?  If so, what is the best way to  
create these?

Thanks for any help or links to resources you can give.  I'm new to  
tdd, so any advice helps!

Cheers,

Julius

-----------------------------------------------------
http://openwetware.org/wiki/User:Lucks
-----------------------------------------------------



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.idyll.org/pipermail/testing-in-python/attachments/20070424/e24a3f1d/attachment.htm 


More information about the testing-in-python mailing list