Search code examples
pythontddinner-classespython-unittest

How to write inner class test method in Python with Unittest


In Java when doing unit testing it is common to have a test class that contains multiple inner classes for each method of the class to test. Each inner class can have multiple testing methods to test a specific functionality of the related method.

I am trying to do the same thing in Python with unittest, but it seems that the inner classes' methods are not executed. For example:

import unittest

class OuterTestClass(unittest.TestCase):

    print("start outer class")

    def test_should_do_something(self):

            self.assertTrue( True )

            print("outer method test completed")

    class InnerTestClass(unittest.TestCase):

        print("start inner class")

        def test_should_do_something(self):

            self.assertTrue( True )

            print("inner method test completed")


Expected behavior:

> start outer class
> start inner class
> inner method test completed
> outer method test completed

Actual behavior:

> start outer class
> start inner class
> outer method test completed

Is it possible to execute the inner class methods as well with unittest ?


Solution

  • You can create a new test method in OuterTestClass that builds a suite of all test cases contained in InnerTestClass.

    class OuterTestClass(TestCase):
    
        print("start outer class")
    
        def test_should_do_something(self):
    
            self.assertTrue( True )
    
            print("outer method test completed")
    
        class InnerTestClass(TestCase):
    
            print("start inner class")
    
            def test_should_do_something(self):
    
                self.assertTrue( True )
    
                print("inner method test completed")
    
        def test_inner_test_class(self):
            suite = unittest.defaultTestLoader.loadTestsFromTestCase(self.InnerTestClass)
            unittest.TextTestRunner().run(suite)