【发布时间】:2015-01-12 17:17:34
【问题描述】:
我想测试我写的一个Python类,如下:
from external_library import GenericClass
class SpecificClass(GenericClass):
def __init__(self, a, b, c):
super(SpecificClass, self).__init__(a, b)
self.c = c
def specific_method(self, d):
self.initialize()
return d + self.c + self.b + self.a.fetch()
GenericClass 由外部库 (external_library) 定义:
class GenericClass(object):
def __init__(self, a, b):
self.a = a
self.b = b + "append"
def initialize(self):
# it might be an expensive operation
self.a.initialize()
def specific_method(self, d):
raise NotImplementedError
我应该如何测试specific_method?除了GenericClass.initialize,我应该将GenericClass作为一个整体、GenericClass.__init__、super或GenericClass.a和GenericClass.b进行模拟吗?还是我解决问题的方法完全错误?
请使用mock 作为模拟库,pytest 作为测试框架。解决方案需要兼容Python2.6+。
提前致谢。
【问题讨论】:
标签: python testing mocking pytest