[英]How to make sure that a function doesn't get called using Mock in a Django Application
我已经浏览了模拟文档,并且看到了一些使用模拟的示例。 但是,作为一个新手,我发现很难在测试中使用模拟。
test_scoring.py
我正在创建一个测试以确保每当我创建一个项目时都不会调用该函数。
我要模拟的功能compute_score()
是HistoryItem
类的一部分。
我到目前为止得到的是:
#test_scoring.py
@mock.patch('monitor.report.history_item.HistoryItem.compute_score')
def test_save_device_report(self):
....
result = factory.create_history_item(jsn)
# If the mocked method gets called after the above function is used, then there should be an error.
那么,我该如何模拟该方法? 我对如何使用它很困惑,因为我发现的资源有不同的方式。
非常感谢您的帮助。
当使用patch方法作为装饰器时,您需要为测试函数指定第二个参数:
@mock.patch('monitor.report.history_item.HistoryItem.compute_score')
def test_save_device_report(self, my_mock_compute_score):
....
# Assuming the compute_score method will return an integer
my_mock_compute_score.return_value = 10
result = factory.create_history_item(jsn)
# Then simulate the call.
score = result.compute_score() # This call could not be necessary if the previous
# call (create_history_item) make this call for you.
# Assert method was called once
my_mock_compute_score.assert_called_once()
# Also you can assert that score is equal to 10
self.assertEqual(score, 10)
请注意,仅当您在其他测试中测试了修补的方法或对象时,才应使用模拟程序。
在哪里打补丁? -> https://docs.python.org/3/library/unittest.mock.html#where-to-patch
编辑
该补丁将避免真正调用compute_score()
。 但是,重新阅读您的文章后,我可以看到您想断言您的函数没有被调用。
希望您创建的每个模拟中都存在called
属性,因此您可以使用:
@mock.patch('monitor.report.history_item.HistoryItem.compute_score')
def test_save_device_report(self, my_mock_compute_score):
...
result = factory.create_history_item(jsn)
self.assertFalse(my_mock_compute_score.called)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.