我嘲笑了以下函数 os.getenv ,但是没有获得我指定的return_value,而是返回了模拟对象本身。我在这里做什么错了?
@staticmethod
def setup_api_key():
load_dotenv() # loading apikey and secret into PATH Variables
api = os.getenv('APIKEY')
secret = os.getenv('SECRET')
return api, secret
测试如下:
def test_setup_api_key(self):
with patch('os.getenv') as mocked_getenv:
mocked_getenv = Mock()
mocked_getenv.return_value = '2222'
result = Configuration.setup_api_key()
self.assertEqual(('2222', '3333'), result)
答案 0 :(得分:1)
当您以上下文管理器方式使用patch
时,获得的对象(mocked_getenv
)已经是Mock
对象,因此您不必重新创建它:>
def test_setup_api_key(self):
with patch('os.getenv') as mocked_getenv:
mocked_getenv.return_value = '2222'
result = Configuration.setup_api_key()
self.assertEqual(('2222', '3333'), result)
您可以通过在创建上下文管理器时直接提供返回值来简化此代码:
def test_setup_api_key(self):
with patch('os.getenv', return_value='2222') as mocked_getenv:
result = Configuration.setup_api_key()
self.assertEqual(('2222', '3333'), result)