jer*_*rgh 5 python unit-testing mocking python-3.x
我正在为我的项目创建单元测试。
我有一个名为 TimerHandler 的类需要测试。该类使用一个名为 AudioHandler 的类。这两个类都是单例类。请参阅下面的代码。
定时器处理程序.py
class TimerHandler(metaclass=Singleton):
def play(self):
# some code that needs to be tested
AudioHandler().start()
Run Code Online (Sandbox Code Playgroud)
音频处理程序.py
class AudioHandler(metaclass=Singleton):
def start(self):
# some code that connects with an audio device
Run Code Online (Sandbox Code Playgroud)
我正在尝试模拟 AudioHandler 的 start 方法,因此它只会返回 None 并且不会尝试连接到音频设备。单元测试如下所示:
@patch.object(AudioHandler, 'start', return_value=None)
def test_play_pause(self, start):
self.timer_handler.play()
Run Code Online (Sandbox Code Playgroud)
问题是它仍然在运行AudioHandler中原来的start函数中的代码。
如何编写一个测试函数来删除/模拟 AudioHandler 中启动函数的功能?
提前致谢
小智 0
您应该从导入它的模块路径模拟一个类
@patch('timer_handler.AudioHandler')
Run Code Online (Sandbox Code Playgroud)
之后,您可以将方法添加到模拟对象中
请阅读 https://docs.python.org/3/library/unittest.mock.html#where-to-patch
| 归档时间: |
|
| 查看次数: |
1595 次 |
| 最近记录: |