首页 > 解决方案 > 如何模拟同一类的嵌套函数调用

问题描述

在帖子中如何模拟嵌套函数?用户模拟一系列用户调用。就我而言,我的情况如下:

class myClass:

    def __init__(self, my_type):
        self.type = my_type

    def output(self):
        self.create_figure()

    def create_figure():
        if self.type == 'A':
            do_A()
        elif self.type == 'B':
            do_B()

    def do_A():
        pass

    def do_B():
        pass

我正在尝试编写一个单元测试来测试是否调用了正确的东西。例如:我想确保当用户调用时outputmyClass('A')调用create_figuredo_A()调用。

我目前正在使用 pytest 进行如下测试:

import myModule, pytest
from unittest.mock import patch

@pytest.fixture()
def default_my_class():
    return myModule.myClass(my_type='A')

@patch('myModule.myClass.do_A')
@patch('myModule.myClass.create_figure')
def test_chart(mock_create_figure, mock_do_a, default_my_class):
    default_my_class.output()
    mock_create_figure.assert_called_once()
    mock_do_a.assert_called_once()

标签: pythonmockingpytest

解决方案


推荐阅读