【问题标题】:Python mock() not mocking the return valuePython mock() 不模拟返回值
【发布时间】:2015-09-09 23:16:37
【问题描述】:

我在使用 Python mock() 时遇到了一些问题,而且我还不够熟悉,无法弄清楚它发生了什么。

我有一个抽象的异步任务类,看起来像:

class AsyncTask(object):
    @classmethod
    def enqueue(cls):
        ....
        task_ent = cls.createAsyncTask(body, delayed=will_delay)
        ....

我想为此类的特定实例修补 createAsyncTask 方法。

我写的代码是这样的:

@patch.object(CustomAsyncTaskClass, "createAsyncTask")
def test_my_test(self, mock_create_task):
    ....
    mock_create_task.return_value = "12"
    fn()    # calls CustomAsyncTaskClass.enqueue(...)
    ....

当我在 enqueue 中打印 task_ent 时,我得到 <MagicMock name='createAsyncTask()' id='140578431952144'>

当我在队列中打印出cls.createAsyncTask 时,我得到<MagicMock name='createAsyncTask' id='140578609336400'>

我做错了什么?为什么 createAsyncTask 不返回 12?

【问题讨论】:

  • ack,忽略这个——我有一些倒退的论据。我不知道如何删除问题,对不起=(
  • 如果你写下答案(不管多么荒谬)并接受它会更好。

标签: python unit-testing python-unittest python-mock magicmock


【解决方案1】:

尝试以下方法:

@patch("package_name.module_name.createAsyncTask")
def test_my_test(self, mock_create_task):
    ....
    mock_create_task.return_value = "12"
    fn()    # calls CustomAsyncTaskClass.enqueue(...)
    ....

其中module_name 是包含AsyncTask 类的模块的名称。

一般来说,这是指导方针https://docs.python.org/3/library/unittest.mock.html#where-to-patch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 2015-10-13
    • 1970-01-01
    • 2021-12-02
    • 2017-04-03
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多