如何模拟 python class 中的变量?

How can you mock a variable inside of python class?

我有一个 Python class,我正在尝试在我的单元测试中模拟某个变量。 我的摘录 Python class:

class something:
    def __init__(self):
        self._commandline = 'dir'

    def run_function(self):
        pass

在我的单元测试中,我试图将 class 变量 _commandline 设置为类似“dirx”的东西,这样当我调用使用 subprocess.run 的 run_function() 时,它会失败并抛出 subprocess.CalledProcessError 以便我可以测试我的断言。

第一次做TDD,如果有更好的方法请指教。 提前致谢!

只需重新分配 _commandLine 变量。

例如

something.py:

class Something:
    def __init__(self):
        self._commandline = 'dir'

    def run_function(self):
        print(self._commandline)
        pass

test_something.py:

import unittest
from something import Something


class TestSomething(unittest.TestCase):
    def test_run_function(self):
        instance = Something()
        instance._commandline = 'dirx'
        instance.run_function()


if __name__ == '__main__':
    unittest.main()

测试结果:

dirx
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK