python - 如何使用 assertRaises() 捕获 "TypeError"

标签 python unit-testing assert

我想捕获代码产生的 TypeError,但不幸的是,unittest 失败了:

代码如下:

import unittest                                                                 

class _Foo(object):                                                             
    def __init__(self):                                                         
        self.bar = ['AAA']                                                      

    def _validate_bar(self, bar):                                               
        if not isinstance(bar, list):                                           
            raise TypeError                                                     
        return True                                                             

class Foo(_Foo):                                                                
    def __init__(self, bar=None):                                               
        super(Foo, self).__init__()                                             
        if bar and self._validate_bar(bar):                                     
            self.bar = bar                                                      

class FooTest(unittest.TestCase):                                               

    def test_bar_as_string(self):                                               
        self.assertRaises("TypeError", Foo("a"))                                

    #def test_a(self):                                                          
    #    try:                                                                   
    #        Foo('a')                                                           
    #    except Exception as exc:                                               
    #        self.assertEqual('TypeError', exc.__class__.__name__)              

    #def test_bar_as_string(self):                                              
    #    with self.assertRaises("TypeError"):                                   
    #        Foo("a")                                                           

if __name__ == "__main__":                            

这里是错误:

test_bar_as_string (__main__.FooTest) ... ERROR

======================================================================
ERROR: test_bar_as_string (__main__.FooTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 21, in test_bar_as_string
    self.assertRaises("TypeError", Foo("a"))
  File "test.py", line 15, in __init__
    if bar and self._validate_bar(bar):
  File "test.py", line 9, in _validate_bar
    raise TypeError
TypeError

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

FAILED (errors=1)



    unittest.main(verbosity=2)   

最佳答案

取消引用 TypeError 并且不直接调用 Foo,而是传递函数(class Foo)和参数。

def test_bar_as_string(self):                                               
    self.assertRaises(TypeError, Foo, "a")

或者,您可以使用 assertRaises 作为上下文管理器:

def test_bar_as_string(self):                                               
    with self.assertRaises(TypeError):
        Foo("a")                                

关于python - 如何使用 assertRaises() 捕获 "TypeError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843336/

相关文章:

python - 获取指向包含某些文本的标签的xpath

c# - 使用inlinedata时是否可以使用string.empty?

java - 线程中的junit断言引发异常

java - Java 开源操作系统

python - 选择嵌套字典并将其转换为 Python 中的 DataFrame

python - 将字符串格式化为仅在 python 中的单词之间有 n 个空格

unit-testing - 自动化测试方法

python - 将测试标记为从 pytest 中的 fixture 内部通过

python-3.x - 我想知道如何使用断言来保证列表列表中的所有元素都具有相同的长度

Python 2.7 在列表列表中查找最小值、最大值