簡體   English   中英

如何在單元測試中使用python Mock side_effect作為Class方法

[英]How to use python Mock side_effect to act as a Class method in unit test

我在python中測試一個自定義API來發出http請求,但我不希望每次運行單元測試時都向真實的外部系統發出請求。 我正在使用帶有side_effect函數的python模擬庫來動態偽造API響應。 如何讓side_effect方法像類方法一樣?

import requests

class MyApiClass():
    def make_request(self, params):
        return requests.get('http://someurl.com', params=params)

    def create_an_object(self, params):
        return self.make_request(params)

import unittest, mock

def side_effect_func(self, params):
    if params['name'] == 'Specific Name':
        return {'text': 'Specific Action'}
    else:
        return {'text': 'General Action'}

class MyApiTest(unittest.TestCase):
    def setUp(self):
        super(MyApiTest, self).setUp()
        mocked_method = mock.Mock(side_effect=side_effect_func)
        MyApiClass.make_request = mocked_method

    def test_create_object(self):
        api = MyApiClass()
        params = {'name': 'Specific Name'}
        r = api.create_an_object(params) # Complains that two arguments are needed!
        self.assertEqual(r['text'], 'Specific Action')

我收到這個錯誤

TypeError: side_effect_func() takes exactly 2 arguments (1 given)

但是我想讓side_effect_func傳遞api作為第一個參數。 感謝任何幫助!

最簡單的方法可能是讓你的mock方法接受一個參數,然后在mock方法本身內靜態引用MyApiClass 否則,您可以嘗試模擬類對象本身(基本上是創建一個模擬元類)或者可能使用一個使用partial的工廠來動態構建一個模擬類方法。 但是如果單個參數/靜態引用方法對你有效,那對我來說似乎是最好的。

此外,從模擬文檔中,有一個使用補丁的模擬未綁定方法 ,看起來它可能更符合您的需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM