Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python assertRaises的奇怪行为(TestCase)_Python_Python 3.x_Unit Testing - Fatal编程技术网

Python assertRaises的奇怪行为(TestCase)

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

我一直在尝试/学习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(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")