【问题标题】:Class code coverage is 100% but unit test file is not类代码覆盖率是 100%,但单元测试文件不是
【发布时间】:2022-07-04 23:28:44
【问题描述】:

我有一个类对象 (my_object),该类中的方法都包含在我的单元测试中。然而,单元测试文件本身有一些代码行遗漏。这些代码行是异常处理程序。

例如下面的单元测试:

def test_remove_file(self):
 my_object.put_file(my_file)
  try:
     my_object.check_file_exists(my_file)
  except Exception:
     assert False
  response = my_object.remove_file(my_file)
  assert response == True

覆盖率报告说异常处理程序丢失。我怎样才能防止这种情况,什么是 在单元测试中没有涵盖这个的含义?

【问题讨论】:

  • 我建议从覆盖率报告中排除测试,这些测试是为了提供对“真实”代码的覆盖......包括覆盖率统计中的测试本身会扭曲数字并且是没有帮助
  • 引发任何异常(不仅仅是AssertionError)的测试被认为是失败的测试。没有理由为了引发另一个异常而捕获一个异常。

标签: python pytest code-coverage


【解决方案1】:

my_object.check_file_exists 引发的异常导致失败,而不是捕获它并在其位置引发AssertionError

def test_remove_file(self):
    my_object.put_file(my_file)
    my_object.check_file_exists(my_file)
    assert my_object.remove_file(my_file)

assert 语句的唯一目的是将my_object.remove_file 的非真返回值转换为异常。

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2017-03-30
    • 2012-01-18
    • 2023-03-28
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    相关资源
    最近更新 更多