我试图编写测试以确保我的程序在给定特定输入的情况下生成特定输出。我已经成功地模拟了我想要测试的输入,但我还没有能够模拟输出功能。我对我尝试的事情及其错误留下了一些评论。我怎样才能使这些测试工作?
这是我的测试:
from src_dir import my_class
class Mock_Dependency:
def __init__( self ):
pass
def print_stuff( self, stuff ):
##return MagicMock() - does not have attribute called
return stuff
@fixture
@patch('src_dir.dependency.Dependency, Mock_Dependency)
def subject():
return my_class.My_Class()
##@patch('subject.print_stuff', MagicMock) - No module named subject
##@patch('my_class.My_Class.print_stuff', MagicMock) - does not have attribute print stuff
def test_print_stuff_was_called( subject ):
assert subject.print_stuff.called
def test_print_stuff_printed( subject ):
assert subject.print_stuff == 'a word'
这是我的班级:
from dependency import Dependency
class My_Class:
def __init__( self ):
self.print_stuff = Dependency.print_stuff()
def run( self ):
self.print_stuff('a word')
答案 0 :(得分:1)
我的问题的解决方案是在收到夹具print_stuff
后在测试函数内部模拟subject
:
def test_print_stuff_was_called( subject ):
with patch.object(subject, 'print_stuff') as mock:
subject.run()
mock.assert_called_with('a word') # pass
mock.assert_called_with('anything else') # fail