Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Pytest中使用Mock替换实例变量而不使用getter方法_Python_Unit Testing_Mocking_Pytest - Fatal编程技术网

Python 如何在Pytest中使用Mock替换实例变量而不使用getter方法

Python 如何在Pytest中使用Mock替换实例变量而不使用getter方法,python,unit-testing,mocking,pytest,Python,Unit Testing,Mocking,Pytest,我试图为类“Process”的方法编写一个测试,如下所示: [main.py] class Process: def run(self): p = Print() if p.get_foo() is True: p.print_hoge() class Print: def __init__(self): # I would like to replace this variable to use mock

我试图为类“Process”的方法编写一个测试,如下所示:

[main.py]
class Process:
    def run(self):
        p = Print()
        if p.get_foo() is True:
            p.print_hoge()

class Print:
    def __init__(self):
        # I would like to replace this variable to use mock
        self.foo = True

    # I would not like to declare
    def get_foo(self):
        return self.foo
    
    def print_foo(self):
        print(self.foo)
这是我的测试代码

import main
import pytest
from pytest import mark


def test_run(mocker):
    test = mocker.patch("main.Print.print_hoge")
    mocker.patch("main.Print.get_foo", return_value=False)
    p = main.Process()
    p.run()
    test.assert_called()
如您所知,我将值True“self.foo”更改为False,并将“mocker.patch”用于“Print.get_foo”。 这看起来并不简单,因为我直接将值“self.foo”替换为mock实例变量。 我不想声明方法“get_foo”


有没有更好的方法来满足我的要求?

如果你不需要测试
Print
的真正功能,你可以模拟
Print
本身,并在模拟中设置
foo
的值。@Beanbremen先生谢谢你的评论。我用你说的话解决了这个问题。