Skip to main content
 首页 » 编程设计

python之使用 pyunit 在 Python 中测试异常

2025年05月04日9mate10pro

我需要测试我的 python 代码是否有异常,但我似乎无法运行正确的语句。
当我测试我的生产代码时,我可以看到异常被抛出,但是当我在我的单元测试文件中测试这个异常时,我得到这个:

testincorrectparam (unittestearnings.TestEarningsArgs) 
should raise error when param not an integer ... "3v" is not a valid argument.  i should be an integer 
ERROR 

我在 SO 上通读了类似的问题,但我无法为我的问题找到满意的答案..

生产代码如下所示:

class Earnings(): 
 
    def printd(i=0): 
 
        try: 
            i = int(i) 
 
        except Exception: 
            print('"' + i + '"' + " is not a valid argument.  i should be an integer") 
            sys.exit(0) 

单元测试代码是这样的:

from earnings import Earnings 
import unittest 
 
class TestEarningsArgs(unittest.TestCase): 
 
   def testincorrectparam(self): 
      '''should raise error when param not an integer''' 
      e = Earnings() 
      value = "3v" 
      self.assertRaises(Exception, e.printd(i=value)) 
 
if __name__ == "__main__": 
      unittest.main() 

非常感谢任何帮助。

请您参考如下方法:

问题是异常被捕获,它没有传播到单元测试。您需要删除 try-except 语句并保留 i = int(i)。在这种情况下,将引发异常,assertRaises 将自己捕获它。

另一个问题是代码中的 sys.exit(0) 行。您需要用 raise Exception(...) 替换它,这不好,因为 Exception 类不是特定的异常(您应该针对预期会发生错误的情况引发更具体的异常)。