为什么我在使用Python3.4';的‘unitest’库时出现AttributeError?
问题描述
下面是我的代码:
import unittest
class Primes:
@staticmethod
def first(n):
<python code here>
class Test(unittest.TestCase):
def __init__(self):
pass
def assert_equals(self, l, m):
self.assertEqual(l, m)
Test = Test()
Test.assert_equals(Primes.first(1), [2])
每当我运行代码时,都会收到以下错误:
Traceback (most recent call last):
File "firstNPrimes.py", line 37, in <module>
Test.assert_equals(Primes.first(1), [2])
File "firstNPrimes.py", line 34, in assert_equals
self.assertEqual(l, m)
File "/usr/lib/python3.4/unittest/case.py", line 796, in assertEqual
assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python3.4/unittest/case.py", line 777, in _getAssertEqualityFunc
asserter = self._type_equality_funcs.get(type(first))
AttributeError: 'Test' object has no attribute '_type_equality_funcs'
我不明白这里有什么问题。
解决方案
您收到该错误是因为您没有正确使用unittest
。根据the example in the docs,您的测试应如下所示:
import unittest
class TestPrimes(unittest.TestCase):
def test_singlePrime_returnsListContainingTwo(self):
self.assertEqual(Primes.first(1), [2])
def test_whateverCase_expectedOutcome(self):
self.assertEqual(Primes.first(...), ...)
if __name__ == '__main__': # optional, but makes import and reuse easier
unittest.main()
您不能只自己实例化测试用例类并调用方法,这会跳过所有测试发现和设置。
相关文章