如何使用assertRaises()对python类的一个u init_uu()方法进行单元测试?

2024-09-28 21:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节课:

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

为什么?我应该在哪里定义这个错误对象?我以为它是内置的默认异常类型,不是吗?


Tags: toselfiffooinitisdef错误
3条回答

我想你是在考虑Exceptions。请用Exception替换描述中的Error一词,这样就可以了:-)

本例中的“Error”可以是任何异常对象。我想您可能已经读过一个代码示例,它将它用作元语法占位符,意思是“适当的异常类”。

所有异常的基类称为“Exception”,其大多数子类是所涉及错误类型的描述性名称,例如“OSError”、“ValueError”、“NameError”、“type error”。

在这种情况下,适当的错误是“value error”(foo的值是错误的,因此是ValueError)。我建议在脚本中将“Error”替换为“ValueError”。

下面是您试图编写的代码的完整版本,我复制了所有内容,因为您的原始示例中有一个奇怪的关键字参数,似乎与赋值相冲突,我使用了“fail除非”函数名,因为这是函数的非别名:

class MyClass:
    def __init__(self, foo):
        if foo != 1:
            raise ValueError("foo is not equal to 1!")

import unittest
class TestFoo(unittest.TestCase):
    def testInsufficientArgs(self):
        foo = 0
        self.failUnlessRaises(ValueError, MyClass, foo)

if __name__ == '__main__':
    unittest.main()

输出为:

.
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK

其他单元测试框架修复的单元测试库“unittest”中存在缺陷。您将注意到,无法从调用上下文访问异常对象。如果要修复此问题,必须在UnitTest的子类中重新定义该方法:

这是一个正在使用的示例:

class TestFoo(unittest.TestCase):
    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        try:
            callableObj(*args, **kwargs)
        except excClass, excObj:
            return excObj # Actually return the exception object
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
            raise self.failureException, "%s not raised" % excName

    def testInsufficientArgs(self):
        foo = 0
        excObj = self.failUnlessRaises(ValueError, MyClass, foo)
        self.failUnlessEqual(excObj[0], 'foo is not equal to 1!')

我从python2.5的unittest.py复制了failUnlessRaises函数,并对其进行了一些修改。

这个怎么样:

class MyClass:
    def __init__(self, foo):
        if foo != 1:
            raise Exception("foo is not equal to 1!")

import unittest

class Tests(unittest.TestCase):
    def testSufficientArgs(self):
        foo = 1
        MyClass(foo)

    def testInsufficientArgs(self):
        foo = 2
        self.assertRaises(Exception, MyClass, foo)

if __name__ == '__main__':
    unittest.main()

相关问题 更多 >