【问题标题】:Python 3 unit-testing, create mock of singleton class functionPython 3 单元测试,创建单例类函数的模拟
【发布时间】:2017-11-25 20:03:11
【问题描述】:

我正在为我的项目创建单元测试。

我有一个需要测试的名为 TimerHandler 的类。此类使用一个名为 AudioHandler 的类。这两个类都是单例。请参阅下面的代码。

timer_handler.py

class TimerHandler(metaclass=Singleton):

    def play(self):
        # some code that needs to be tested

        AudioHandler().start()

audio_handler.py

class AudioHandler(metaclass=Singleton):

    def start(self):
        # some code that connects with an audio device

我正在尝试模拟 AudioHandler 的 start 方法,因此它只会返回 None 并且不会尝试连接到音频设备。单元测试如下所示:

@patch.object(AudioHandler, 'start', return_value=None)
def test_play_pause(self, start):

    self.timer_handler.play()

问题是它还在AudioHandler中原来的start函数中运行代码。

如何编写一个测试函数来移除/模拟 AudioHandler 中的 start 函数的功能?

提前致谢

【问题讨论】:

    标签: python python-3.x unit-testing mocking


    【解决方案1】:

    您应该从要导入它的模块路径中模拟一个类

    @patch('timer_handler.AudioHandler')
    

    然后,您可以将您的方法添加到模拟对象

    请阅读 https://docs.python.org/3/library/unittest.mock.html#where-to-patch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2015-09-16
      • 2015-11-13
      • 2010-11-17
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多