在Python中,如何使用voidspace模拟一个对象的一个方法(多个方法中的一个)?
e、 g 我希望控制台能够输出:在Python中,如何使用voidspace模拟一个对象的一个方法(多个方法中的一个)?,python,mocking,Python,Mocking,e、 g 我希望控制台能够输出: class Foobar: def func(): print('This should never be printed.') def func2(): print('Hello!') def test_mock_first_func(): foobar = Foobar() # !!! do something here to mock out foobar.func() foobar
class Foobar:
def func():
print('This should never be printed.')
def func2():
print('Hello!')
def test_mock_first_func():
foobar = Foobar()
# !!! do something here to mock out foobar.func()
foobar.func()
foobar.func2()
好的,显然文档只是在迂回中循环,但事实上本页包含解决方案: 为了补充在示例中使用混淆的变量/函数名称的薄弱文档(文字太多,内容太少…太可惜了),模拟该方法的正确方法是:
Hello!
是否不希望
func()
打印任何内容?只需将print语句替换为pass
?不,这个问题是关于模拟的。假设Foobar类有一个正确的实现:您不应该更改它的代码。您能准确地描述一下“mocking”是什么意思吗?只是想重定向某些函数的输出?具体地说,我希望语法能够实现我的要求,谢谢你的帮助,Cameron Sparr,我想我找到了答案。我只是在大声打字。我相信互联网上的其他人都会喜欢这种理解模仿库的捷径。
class Foobar:
def func():
print('This should never be printed.')
def func2():
print('Hello!')
def test_mock_first_func():
with patch.object(Foobar, 'func', autospec=True) as mocked_function:
foobar = Foobar()
foobar.func() # This function will do nothing; we haven't set any expectations for mocked_function!
foobar.func2()