[TIP] mocking out mixins and subclasses
Nate Lowrie
solodex2151 at gmail.com
Mon Mar 5 12:45:42 PST 2007
On 3/5/07, Michael Foord <fuzzyman at voidspace.org.uk> wrote:
> Nate Lowrie wrote:
> > I have several mixin classes that are subclassed by other classes. I
> > am unit testing the mixin classes on there own. Some of the classes
> > that subclass these mixins call the mixin functions in some of the
> > methods. I know that I can rebind the methods to mocked function
> > after I instantiate an object but there are some calls to the mixin
> > methods in the init section as well. Ideally, I would like to mock
> > the mixin before creating any objects.
> >
> > How are other people handling unit testing for mixins and objects
> > using the mixin? Is there an easy way to do this that I am
> > overlooking?
> >
> Hmm... mocking out base classes before instantiation is something I
> haven't had to do.
>
> As the code snippet below shows, you can do it by assigning to
> '__bases__', to swap out the base class.
>
> >>> class x(object):
> ... z = 3
> ...
> >>> class y(object):
> ... z = 6
> ...
> >>> class z(x):
> ... pass
> ...
> >>> z.z
> 3
> >>> z.__bases__
> (<class '__main__.x'>,)
> >>> z.__bases__ = (y,)
> >>> z.z
> 6
>
> So you should be able to swap out the base class before instantiating
> your object - this will work so long as the mixin methods are called
> using 'self'.
Thanks. All of the mixin methods are being called with self.
>
> If the calls in init reference the class by name (rather than self),
> then you can just mock on the base class of course.
>
> HTH
>
> Fuzzyman
> http://www.voidspace.org.uk/python/index.shtml
>
> > Cheers,
> >
> > Nate L.
> >
> > _______________________________________________
> > testing-in-python mailing list
> > testing-in-python at lists.idyll.org
> > http://lists.idyll.org/listinfo/testing-in-python
> >
> >
>
>
More information about the testing-in-python
mailing list