assertRaises没有捕获异常

时间:2012-11-08 20:50:55

标签: python unit-testing

我有一个单元测试,用于检查构造函数中的异常:

import unittest
from jaboci import Jacobi

class TestJacobi(unittest.TestCase):

    def test_even(self):
        a = 11
        n = 12
        Jacobi(a, n)
        self.assertRaises(ValueError, Jacobi, a, n)

if __name__ == '__main__':
    unittest.main()

受测试的课程:

class Jacobi:

    def __init__(self, a, n):
        self.a = a
        self.n = n
        if n % 2 == 0:
            raise ValueError("N must be odd.")

当我使用-m unittest discover运行unittest时,测试失败:

E
======================================================================
ERROR: test_even (test_jacobi.TestJacobi)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/prasopes/prg/python/PycharmProjects/jacobi_symbol/test_jacobi.py", line 9, in test_even
    Jacobi(a, n)
  File "/home/prasopes/prg/python/PycharmProjects/jacobi_symbol/jaboci.py", line 7, in __init__
    raise ValueError("N must be odd.")
ValueError: N must be odd.

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

2 个答案:

答案 0 :(得分:4)

您在Jacobi(a, n)之前致电self.assertRaises(ValueError, Jacobi, a, n)。您获得的例外是第一次调用,因此测试立即失败。它永远不会到达assertRaises

答案 1 :(得分:0)

[由于我没有足够的代表评论@mata答案...]

为了清楚起见,你需要

  • 删除Jacobi(a, n) [暗示@mata]
  • 或者,叫'Jacobi(n,a)'[由@abarnert对@mata发表评论]