在不运行 __init__ 的情况下测试实例方法的最佳方法

Ken*_*Far 5 python unit-testing

我有一个简单的类,它通过 init 获取它的大部分参数,它还运行各种完成大部分工作的私有方法。输出可通过访问对象变量或公共方法获得。

这就是问题所在——我希望我的 unittest 框架直接调用 init 调用的私有方法,并使用不同的数据——而无需通过 init.d 。

做到这一点的最佳方法是什么?

到目前为止,我一直在重构这些类,以便 init 做更少的事情并且单独传入数据。这使测试变得容易,但我认为该类的可用性受到了一些影响。

编辑:基于伊格纳西奥回答的示例解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 5

对于新式类,调用object.__new__(),将类作为参数传递。对于旧式类,调用types.InstanceType()将类作为参数传递。

import types

class C(object):
  def __init__(self):
    print 'init'

class OldC:
  def __init__(self):
    print 'initOld'

c = object.__new__(C)
print c

oc = types.InstanceType(OldC)
print oc
Run Code Online (Sandbox Code Playgroud)