模拟方法的返回值不起作用

时间:2019-11-16 18:50:49

标签: python-3.x mocking python-mock

在测试create_response方法时,我似乎无法嘲笑get_external_response方法的返回值。

/ foo / response

from abc import ABCMeta, abstractmethod


def create_response(url, type):
    query = create_query(url, type)
    external_response = get_external_response(query)  <-- what I want to mock
    return external_response

def create_query(url, type):
    cc = MyFactory
    return cc.get_concrete_class(url, type)

def get_external_response(cc):
    return cc.make_query()


class MyAbstractClass(metaclass=ABCMeta):
    def __init__(self, url, type):
        self.url = url
        self.type = type
        self.query = self.make_query()

    @abstractmethod
    def make_query(self):
        pass

class MyFactory:
    @staticmethod
    def get_concrete_class(url, type):
        if type == 'A':
            return MyClass(url, type)
        else:
            print("not valid type")

class MyClass(MyAbstractClass):
    def __init__(self, url, type):
        super().__init__(url, type)

    def make_query(self):
        return self.url + self.type


if __name__ == '__main__':
    result = create_response('www.stackoverflow.com', 'A')
    print(result)

如果执行上述操作,则会得到预期的www.stackoverflow.comA

但是,如果尝试模拟get_external_response的返回值,它似乎无济于事:它仍然返回www.stackoverflow.comA,下面的断言失败。

/ foo / test_response

from foo.response import create_response
import pytest
from unittest import mock


def test_create_response():
    mock_external_response = mock.Mock()
    mock_external_response.create_flask_response.return_value = 'www'

    result = create_response('www.stackoverflow.com', 'A')
    assert result == 'www'

我不明白为什么未设置返回值,因为调用create_response时,它将最终达到调用create_flask_response的地步,如果我没有记错的话,它应该返回{ {1}},因为我已经嘲笑了。

有人可以解释我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

我注意到您正在函数内部创建Mock对象,但实际上并未使用Mock。 看来您需要在使用Mock的地方修补该函数。

/ foo / test_response

@mock.patch('foo.response.get_external_response')
def test_create_response(mock_get_external_reponse):
    mock_get_external_response.return_value = 'www'         # This is a Mock object, but will be used as a patch over the actual function where it is used

    result = create_response('www.stackoverflow.com', 'A')
    assert result == 'www'

为方便起见,快速链接到相关文档部分:

模拟和补丁简介: https://docs.python.org/3/library/unittest.mock.html#quick-guide

此处专门修补 https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch