获取在单元测试期间调用的方法的值

Get value a method was called with during unit test

我正在使用 pytest_mock 模拟函数调用。我想检查对 doB() 的调用,看看它是否是用值 3 调用的。我将如何为此编写断言?

def testtest(mocker):
    # arrange
    mocker.patch.object(ClassA, 'doB', return_value=None)
    sut = ClassA()
    # act
    actual = sut.party(4) # will make a call to doB
    expected = 3
    # assert

可能是这样的:

def testtest(mocker):
    # arrange
    mocked_doB = mocker.patch.object(ClassA, 'doB', return_value=None)
    sut = ClassA()
    # act
    actual = sut.party(4) # will make a call to doB
    expected = 3
    # assert
    mocked_doB.assert_called_once_with(expected)

如果您为模拟对象赋值,在本例中为变量 mocked_doB,您将得到一个 MagicMock 对象。使用此 MagicMock 对象,您可以访问 unittest.mock Mock class 中的所有类型的方法,例如

  • assert_called_once_with()
  • call_count,
  • 还有更多...

看这里:https://docs.python.org/3/library/unittest.mock.html#the-mock-class

这是可行的,因为使用 pytest-mock 框架,您可以直接从 mocker 访问 mock 模块。 这在“用法”下说明,https://pypi.org/project/pytest-mock/