【发布时间】:2014-08-06 12:51:23
【问题描述】:
假设我有几个这样的测试:
class TestMyTest(unittest.TestCase):
def SetUpClass(cls):
cls.my_lib = MyLib()
def my_first_test(self):
self.my_lib.my_function = Mock(return_value=True)
self.assertTrue(self.my_lib.run_my_function(), 'my function failed')
def my_second_test(self):
# Some other test that calls self.my_lib.my_function...
假设我在 MyLib 中有这样的东西:
class MyLib(Object):
def my_function(self):
# This function does a whole bunch of stuff using an external API
# ...
def run_my_function(self):
result = self.my_function()
# Does some more stuff
# ...
在 my_first_test 中,我正在模拟 my_lib.my_function 并在函数执行时返回 True。在这个例子中,我的断言是调用 run_my_function(),它是同一个库中的另一个函数,除其他外,它调用 my_lib.my_function。但是当执行 my_second_test 时,我不希望调用模拟函数,而是调用真实函数。所以我想我需要在运行 my_first_test 之后以某种方式破坏模拟,可能是在 tearDown() 期间。如何销毁该模拟?
我编辑了我的原始问题以添加更多细节,因为看起来不是那么清楚,对此感到抱歉。
【问题讨论】:
-
您的对象是否在对自己进行测试并模拟自己的实现?那是自找麻烦。通常你有一个测试类(使用内置的
unittest),它与被测试的类不同。编辑 - 这将为每个测试创建一个新的对象实例,因此无需重置状态。 -
我用他的
self.assertTrue来表示这一切都在unittest.TestCase内部,但为了简单起见,它被省略了。如果不是这样,那就大错特错了。 -
@PatrickCollins 但是
self.my_lib.my_function呢?这看起来像是测试对象的实现,或者他在设置中保留了一个对象。也许你是对的,是后者。
标签: python unit-testing mocking python-mock