我一定很累,因为肯定有一种简单的方法可以做到这一点。但是我已经阅读了 pytest 文档并且无法弄清楚这个简单的用例。
我有一个小包要测试:
class MyClass:
def __init__(self):
pass
def my_method(self, arg):
pass
def the_main_method():
m = MyClass()
m.my_method(123)
我想确保(1)创建一个实例,并使用正确的参数调用MyClass
(2) 。my_method
所以这是我的测试:
from unittest.mock import patch
@patch('mypkg.MyClass', autospec=True)
def test_all(mocked_class):
# Call the real production code, with the class mocked.
import mypkg
mypkg.the_main_method()
# Ensure an instance of MyClass was created.
mocked_class.assert_called_once_with()
# But how do I ensure that "my_method" was called?
# I want something like mocked_class.get_returned_values() ...
我知道每次生产代码调用框架时都会产生一个新的模拟实例MyClass()
。unittest
但是我如何获得这些实例呢?
我想写一些类似的东西:
the_instance.assert_called_once_with(123)
但我从哪里得到the_instance
?