Deriving a class from TestCase throws two errors

前端 未结 2 826
广开言路
广开言路 2020-12-10 01:08

I have some basic setup/teardown code that I want to reuse in a whole bunch of unit tests. So I got the bright idea of creating some derived classes to avoid repeating code

相关标签:
2条回答
  • 2020-12-10 01:18

    In BaseController's __init__ you need to call unittest.TestCase's __init__ just like you did in TestMyController.

    The call to construct a TestCase from the framework may be passing an argument. The best way to handle this for deriving classes is:

    class my_subclass(parentclass):
        def __init__(self, *args, **kw):
            parentclass.__init__(self, *args, **kw)
            ...
    
    0 讨论(0)
  • 2020-12-10 01:39

    It's because you're overriding __init__() incorrectly. Almost certainly, you don't want to override __init__() at all; you should do everything in setUp(). I've been using unittest for >10 years and I don't think I've ever overridden __init__().

    However, if you really do need to override __init__(), remember that you don't control where your constructor is called -- the framework calls it for you. So you have to provide a signature that it can call. From the source code (unittest/case.py), that signature is:

    def __init__(self, methodName='runTest'):
    

    The safe way to do this is to accept any arguments and just pass 'em up to the base class. Here is a working implementation:

    class BaseTest(unittest.TestCase):
        def __init__(self, *args, **kwargs):
            unittest.TestCase.__init__(self, *args, **kwargs)
    
        def setUp(self):
            print "Base.setUp()"
    
        def tearDown(self):
            print "Base.tearDown()"
    
    
    class TestSomething(BaseTest):
        def __init__(self, *args, **kwargs):
            BaseTest.__init__(self, *args, **kwargs)
            self.controller = object()
    
        def test_silly(self):
            self.assertTrue(1+1 == 2)
    
    0 讨论(0)
提交回复
热议问题