Best way to test instance methods without running __init__

Posted by KenFar on Stack Overflow See other posts from Stack Overflow or by KenFar
Published on 2010-05-18T17:08:03Z Indexed on 2010/05/18 18:20 UTC
Read the original article Hit count: 225

Filed under:
|

I've got a simple class that gets most of its arguments via init, which also runs a variety of private methods that do most of the work. Output is available either through access to object variables or public methods.

Here's the problem - I'd like my unittest framework to directly call the private methods called by init with different data - without going through init.

What's the best way to do this?

So far, I've been refactoring these classes so that init does less and data is passed in separately. This makes testing easy, but I think the usability of the class suffers a little.

EDIT: Example solution based on Ignacio's answer:

import types

class C(object):

   def __init__(self, number):
       new_number = self._foo(number)
       self._bar(new_number)

   def _foo(self, number):
       return number * 2

   def _bar(self, number):
       print number * 10

#--- normal execution - should print 160: -------
MyC = C(8)

#--- testing execution - should print 80 --------
MyC = object.__new__(C)
MyC._bar(8)

© Stack Overflow or respective owner

Related posts about python

Related posts about unit-testing