0

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

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.")

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

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)
4

2 回答 2

4

Jacobi(a, n)你之前打电话self.assertRaises(ValueError, Jacobi, a, n)。您得到的异常来自第一次调用,因此测试立即失败。它永远不会达到与assertRaises.

于 2012-11-08T20:54:05.607 回答
0

[因为我没有足够的代表来评论@mata的答案......]

为了清楚起见,您要么需要

  • 删除Jacobi(a, n)[@mata 暗示]
  • 或者,调用 'Jacobi(n, a)' [由@abarnert 对@mata 的评论提出]
于 2012-12-13T03:03:01.287 回答