【问题标题】:How to check a function was called with a spefic argument python如何检查使用特定参数python调用的函数
【发布时间】:2022-01-15 07:07:55
【问题描述】:

我正在编写一个单元测试,我正在尝试检查是否使用正确的参数调用了该函数。有人告诉我,我可以通过嘲笑来做到这一点。这是我的代码

import pytest
from mock import patch
import attr

def adjust(x):
    if x is None:
        return 0
    return x

@attr.s
class Pater():
    only_argument = attr.ib(type=int,converter = adjust)

def foo(pass_only):
    yield Pater(pass_only)

@patch("this_file.Pater")
def test_foo(mock_Pater):
    foo(None)
    mock_Pater.assert_called_with(None)

但我收到以下错误

E           AssertionError: expected call not found.
E           Expected: Pater(None)
E           Actual: not called.

你能告诉我如何正确地做吗?

【问题讨论】:

    标签: python unit-testing mocking pytest


    【解决方案1】:

    您的测试确实没有调用/实例化Pater,因为foo()Pater 生成器,而您还没有从中提取任何项目。换句话说,yield 中的代码在您迭代 foo() 的返回值之前不会执行。

    将您的测试更改为:

    @patch("this_file.Pater")
    def test_foo(mock_Pater):
        next(foo(None))
        mock_Pater.assert_called_with(None)
    

    它会过去的。

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2015-10-16
      • 2020-10-14
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      相关资源
      最近更新 更多