[英]Get value a method was called with during unit test
I am using pytest_mock
to mock a function call.我正在使用pytest_mock
来模拟 function 调用。 I would like to inspect the call to doB()
to see if it was called with the value 3. How would I write the assert for this?我想检查对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
Maybe something like this:也许是这样的:
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)
If you assign a value to the mocked object, in this case variable mocked_doB
, you will get a MagicMock
object back.如果您为模拟的 object 分配一个值,在本例中为变量mocked_doB
,您将返回一个MagicMock
object。 With this MagicMock object, you have access to all kind of methods from the unittest.mock
Mock class, eg使用此 MagicMock object,您可以访问unittest.mock
Mock class 中的所有类型的方法,例如
See here: https://docs.python.org/3/library/unittest.mock.html#the-mock-class见这里: https://docs.python.org/3/library/unittest.mock.html#the-mock-class
This works because with the pytest-mock framework you can directly access the mock
module from mocker
.这是有效的,因为使用 pytest-mock 框架,您可以直接从mocker
访问mock
模块。 This is stated here under "Usage", https://pypi.org/project/pytest-mock/ .这在“用法”下进行了说明, https://pypi.org/project/pytest-mock/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.