代码之家  ›  专栏  ›  技术社区  ›  Sam McAfee

如何使用assertraisses()对python类的\u init \uuu()方法进行单元测试?

  •  21
  • Sam McAfee  · 技术社区  · 16 年前

    我有一堂课:

    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
    

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

    3 回复  |  直到 16 年前
        1
  •  21
  •   Jerub    16 年前

    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
    

    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!')
    

        2
  •  5
  •   Terhorst    16 年前

    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()
    
        3
  •  1
  •   Jon Cage    16 年前