【问题标题】:How can you mock a variable inside of python class?如何在 python 类中模拟变量?
【发布时间】:2021-03-27 21:28:53
【问题描述】:

我有一个 Python 类,我正在尝试在单元测试中模拟某个变量。 我的 Python 课程节选:

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

    def run_function(self):
        pass

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

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

【问题讨论】:

    标签: python python-3.x subprocess python-unittest


    【解决方案1】:

    只需重新分配 _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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 2021-11-16
      • 2020-11-11
      相关资源
      最近更新 更多