我有一节课:
class MyClass:
def __init__(self, foo):
if foo != 1:
raise Error("foo is not equal to 1!")
并且一个单元测试应该确保传递给构造函数的不正确参数正确地引发一个错误:
def testInsufficientArgs(self):
foo = 0
self.assertRaises((Error), myClass = MyClass(Error, foo))
但是我。。。
NameError: global name 'Error' is not defined
为什么?我应该在哪里定义这个错误对象?我以为它是内置的默认异常类型,不是吗?
我想你是在考虑Exceptions。请用Exception替换描述中的Error一词,这样就可以了:-)
本例中的“Error”可以是任何异常对象。我想您可能已经读过一个代码示例,它将它用作元语法占位符,意思是“适当的异常类”。
所有异常的基类称为“Exception”,其大多数子类是所涉及错误类型的描述性名称,例如“OSError”、“ValueError”、“NameError”、“type error”。
在这种情况下,适当的错误是“value error”(foo的值是错误的,因此是ValueError)。我建议在脚本中将“Error”替换为“ValueError”。
下面是您试图编写的代码的完整版本,我复制了所有内容,因为您的原始示例中有一个奇怪的关键字参数,似乎与赋值相冲突,我使用了“fail除非”函数名,因为这是函数的非别名:
输出为:
其他单元测试框架修复的单元测试库“unittest”中存在缺陷。您将注意到,无法从调用上下文访问异常对象。如果要修复此问题,必须在UnitTest的子类中重新定义该方法:
这是一个正在使用的示例:
我从python2.5的unittest.py复制了failUnlessRaises函数,并对其进行了一些修改。
这个怎么样:
相关问题 更多 >
编程相关推荐