假设我们有以下 Python 函数:
def lookup_current_prices_dict(stocks):
prices = {}
for stock in stocks:
prices[stock] = stock_price_toolkit.get_current_price(stock)
return prices
我想为此功能编写单元测试,但我不想依赖于使用 stock_price_toolkit 模块查找的价格。实际上,我想告诉 stock_price_toolkit 在调用 get_current_price() 时始终返回 1.00,这样我就可以测试函数的其余部分.
我知道这可以使用 mock 来完成,但我找不到关于如何完成此特定任务的任何好的文档。
请您参考如下方法:
你可以用 mock.patch 来做到这一点,就像这样:
with patch('sock_price_toolkit.get_current_price') as m:
m.return_value = '1.00'
prices = lookup_current_prices_dict(stocks)
查看官方documentation
