如何模拟同一类的嵌套函数调用

时间:2018-12-19 01:14:40

标签: python mocking pytest

在帖子How to mock nested functions?中,用户模拟了一系列用户调用。就我而言,我遇到以下情况:

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

我正在尝试编写一个单元测试,以测试是否调用了正确的东西。例如:我想确保当用户在output上调用myClass('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()

0 个答案:

没有答案
相关问题