我刚开始使用python模拟框架。我只想计算一个方法被调用的次数,而不消除实际调用该方法的效果。
例如,在这个简单的计数器示例中,我希望两者都递增计数器并跟踪它的调用:
import unittest
import mock
class Counter(object):
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
class CounterTest(unittest.TestCase):
def test_increment(self):
c = Counter()
c.increment()
self.assertEquals(1, c.count)
def test_call_count(self):
with mock.patch.object(Counter, 'increment') as fake_increment:
c = Counter()
self.assertEquals(0, fake_increment.call_count)
c.increment()
self.assertEquals(1, fake_increment.call_count)
# increment() didn't actually get called.
self.assertEquals(1, c.count) # Fails.
if __name__ == '__main__':
unittest.main()
是否可以强制mock
在mocked方法注册调用之后调用它,或者只是表示我想保留mocked函数的效果?
只需使用包装:
如果稍后初始化
c
,可能会出现一些绑定问题,因为传递给wraps
的函数不知道self
。我在mock1方面不是很有经验,但我是通过使用函数包装器而不是默认的
MagicMock
来完成的:当然,这个
FuncWrapper
非常小。它只计算调用次数,然后将流控制委托回原始函数。如果需要同时测试其他东西,则需要添加到FuncWrapper
类中。我还修补了一个类实例,而不是整个类。主要原因是我需要一个FuncWrapper
中的实例方法。事实上,我刚开始学习——认为自己受到了警告;)。
相关问题 更多 >
编程相关推荐