我有一个函数要测试。datahandler参数是我在模块的其他地方定义的类Datahandler的一个实例。
def create_row(row_content, datahandler):
row = {}
# Here comes some code that fills the "row" dictionary based on what was passed in row_content
row = datahandler.process_row(row)
# some more handling happens to the processed row
return row我尝试编写单元测试,但遇到了困难,因为我似乎找不到一种方法来替换模拟数据处理程序的process_row方法:
class TestCreateRow(unittest.TestCase):
def fake_process_row(row):
return row
def test_create_row(self):
# create a suitable row_content here
# row_content = ...
expected = {"first column":"first value", "second column":"second value"}
datahandler = Mock()
# !!! This doesn't work - what is the correct solution?
datahandler.process_row = self.fake_process_row
result = create_row(row_content, datahandler)
self.assertDictEqual(expected, result)我尝试使用return_value和side_effects将fake_process_row函数分配给模拟的数据处理程序,甚至将fake_process_row补丁到Mock中,但是在我尝试的任何语法正确的版本中,当我需要它来实际调用我的fake_process_row函数以便它可以返回实际行时,调用datahandler.process_row(row)仍然返回一个Mock()。
我见过一些解决方案,在测试中,创建了一个真正的datahandler对象,并将fake_process_row修补到其中。我不想这样做,因为实例化真正的类并不是很容易。只有一个“工作”方法的mock会容易得多,就像我可以有一个具有“工作”返回值的属性的mock一样。
发布于 2021-09-21 10:17:13
所以我找到了解决方案,就是创建两个不同的Mock。
def test_create_row(self):
# create a suitable row_content here
# row_content = ...
expected = {"first column":"first value", "second column":"second value"}
datahandler = Mock()
# The magic happens here
method_mock = Mock(side_effect = self.fake_process_row)
datahandler.process_row = method_mock
result = create_row(row_content, datahandler)
self.assertDictEqual(expected, result)使用side_effect有点违反直觉,但它是在访问Mock()时立即发生的。因此,当我们将datahandler.process_row设置为具有此副作用的Mock时,它会在被测代码调用process_row方法时触发,而且它也足够智能,可以正确地传递参数。
https://stackoverflow.com/questions/69221535
复制相似问题