1
在下面的測試代碼中,Generator類包含兩個方法,每個方法都調用Counter類的next_count
方法。爲什麼從生成器中調用模擬對象無法正確測試?
對next_count
的這兩個調用使用assert_called_with
進行了兩次幾乎相同的測試。生成器方法的測試失敗。爲什麼?如何測試此通話?
代碼在測試
generator.py
class Counter:
def __init__(self):
self.count = 1
def next_count(self):
self.count += 1
return self.count
class Generator:
def __init__(self):
self.counter = Counter()
def direct_call(self):
self.counter.next_count()
def iter_event(self):
while True:
yield self.counter.count
self.counter.next_count()
測試模塊
test_generator.py
import unittest
import unittest.mock
import generator
class Generator(unittest.TestCase):
def setUp(self):
p = unittest.mock.patch('generator.Counter')
self.addCleanup(p.stop)
self.mock_counter = p.start()
def test_next_count_called_in_direct_call(self): # Passes
g = generator.Generator()
g.direct_call()
self.mock_counter.assert_called_with()
def test_next_count_called_in_iter_event(self): # Fails
g = generator.Generator()
count_gen = g.iter_event()
next(count_gen)
next(count_gen)
self.mock_counter.next_count.assert_called_with()