【问题标题】:How to pytest a python function with raise exception如何对引发异常的python函数进行pytest
【发布时间】:2019-01-24 06:19:45
【问题描述】:

我的文件夹结构如下所示:

|- src
    |- __init__.py
    |- funcA.py
    |- util.py
|- tests
   |- __init__.py
   |- test_funcA.py
   |- test_util.py

我的目标是在 funcA.py 中测试一个函数

def f():
   try:
     helper()
   except Exception as e:
     raise Exception('error: fail to call helper')

util.py 中的辅助函数

def helper():
   try:
     #do something
   except Exception as e:
     raise Exception('error: fail to do something') 

我为 f() 写的单元测试没有覆盖这两行except Exception as e: raise Exception('error: fail to call helper')

这是我的 f 测试用例

def test__f():
    with mock.patch('src.utils.helper', side_effect=Exception('fail to call helper')):
        from src import funcA
        with pytest.raises(Exception):
            funcA.f()

如何编写单元测试来覆盖 f 的引发异常?谢谢

【问题讨论】:

  • 我不太明白。 “f 的引发异常”是什么意思?
  • 它应该可以工作,除非你有重复的功能名称,否则没有任何问题

标签: python unit-testing exception pytest


【解决方案1】:

我认为“src.utils.helper”是错误的。我猜你应该使用“src.funcA.helper”。

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多