Python assertRaises的奇怪行为(TestCase)
我一直在尝试/学习Python中的单元测试工作,我遇到了这种奇怪的行为,我做错了什么吗 课程Python assertRaises的奇怪行为(TestCase),python,python-3.x,unit-testing,Python,Python 3.x,Unit Testing,我一直在尝试/学习Python中的单元测试工作,我遇到了这种奇怪的行为,我做错了什么吗 课程 class Entity: def __init__(self, n): if not isinstance(n, int): raise TypeError('n must be a number.') self.n = n 测试 from src.entity import Entity class TestEntity(Test
class Entity:
def __init__(self, n):
if not isinstance(n, int):
raise TypeError('n must be a number.')
self.n = n
测试
from src.entity import Entity
class TestEntity(TestCase):
def test__init__types(self):
self.assertRaises(TypeError, Entity.__init__, "2")
self.assertRaises(TypeError, Entity.__init__, 2)
第二个assertRaises
测试不应该失败吗?因为2是一个数字,因此不会引发TypeError
?相反,它表示OK。实体。
接受两个参数:self
和n
。您只提供了一个,并且得到一个TypeError
注意:
>>> class A:
... def __init__(self, n):
... print(n)
...
>>> A.__init__('s')
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'n'
现在,为什么会发生这种情况?从哪里可以得到
self
参数?问题是,\uuuuuu init\uuuuuu
随此参数一起自动提供为A.\uuuu new\uuuuuuu
,因此您可以自己调用A.\uuuuu new\uuuuuuu
,这将导致出现这种奇怪的代码:
self.assertRaises(TypeError, A.__new__(A).__init__, "2")
那么我该如何测试构造函数呢?或者保持调用版本:
self.assertRaises(TypeError,Entity,2)
。课程本身是可以调用的。谢谢你的帮助。
self.assertRaises(TypeError, A.__new__(A).__init__, "2")