首页 > 解决方案 > 如何为接受文件路径作为参数的方法实现 python 单元测试?

问题描述

class A:
    def read_json(self,file_json_path):
        try:
            with open(file_json_path) as fd:
                content = json.dumps(fd)
         except IOError:
            print 'exception while opening a file %s\n'%(file_json_path)

我是 python 新手,任何人都可以指导我,如何模拟打开文件和读取 json 数据。

标签: pythonpython-unittest

解决方案


您需要从 mock 模块查看mock_open 。它可以让你修补内置的 open 方法来伪造读/写。

如果有这个功能(注意我改变了你的功能):

def read_json(file_json_path):
    try:
        with open(file_json_path) as fd:
            content = json.load(fd)
            return content
    except IOError:
        print('exception while opening a file %s\n' % (file_json_path))

您可以使用以下方法轻松测试该功能:

def test_read_json():
    from unittest.mock import mock_open, patch

    m = mock_open(read_data = '{"key": "value"}')
    with patch('__main__.open', m):
        result = read_json('fake_file')
        assert result == {'key': 'value'}
    m.assert_called_once_with('fake_file')


推荐阅读