正如错误消息告诉您的那样,您的断言加注对象没有属性exception
。更具体地说,这个调用:
cm.exception.message
cm
在这种情况下是你的断言对象,并且因为你正在测试的代码实际上从未引发,所以你的cm
对象不会有exception
您尝试访问的属性。
现在,我们来看看为什么会发生这种情况。您正在尝试测试当exception
正在你的身边长大add
方法,为了提高TypeError
。但是,如果您查看测试用例,则会将两个有效整数传递给add
方法。您不会引发异常,因为这是一个有效的测试用例。
对于您的单元测试,您希望测试当您raise
一些东西,即插入无效数据到add
方法。再次尝试您的代码,但这一次在单元测试中,传递以下内容:
add(5, 'this will raise')
您现在将得到您的TypeError
.
您还需要在上下文管理器之外执行断言验证:
def test_upper(self):
with self.assertRaises(TypeError) as cm:
add(3, 'this will raise')
self.assertEqual("Input should be a string:", cm.exception.message, "Input is not a string:")
现在你会遇到另一个问题。没有message
属性。你应该简单地检查一下cm.exception
。此外,在你的add
你的字符串的方法是:
"Input should be a string:"
但是,您正在检查它是否是:
"Input is not a string:"
所以,一旦你更正你的单元测试以使用cm.exception
,您现在将面临:
AssertionError: 'Input should be a string:' != TypeError('Input should be a string:',) : Input is not a string:
因此,您的断言应该通过调用来检查异常字符串str
on the cm.exception
:
self.assertEqual("Input should be a string:", str(cm.exception), "Input should be a string:")
所以,你的完整测试方法应该是:
def test_upper(self):
with self.assertRaises(TypeError) as cm:
add(3, 'this will raise')
self.assertEqual("Input should be a string:", str(cm.exception), "Input should be a string:")