Python unittest.TestCase object has no attribute 'runTest'

28,108

Solution 1

You need to invoke a TestLoader:

if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test)
    unittest.TextTestRunner().run(suite)

Solution 2

You have to specify the test method name (test1):

import unittest

class Test(unittest.TestCase):
    def test1(self):
        assert(True == True)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(Test('test1')) # <----------------
    unittest.TextTestRunner().run(suite)

Or, if you want to run all tests in the file, Just calling unittest.main() is enough:

if __name__ == "__main__":
    unittest.main()
Share:
28,108
Jingguo Yao
Author by

Jingguo Yao

Programmer

Updated on October 29, 2020

Comments

  • Jingguo Yao
    Jingguo Yao over 3 years

    For the following code:

    import unittest
    
    class Test(unittest.TestCase):
        def test1(self):
            assert(True == True)
    
    if __name__ == "__main__":
        suite = unittest.TestSuite()
        suite.addTest(Test())
        unittest.TextTestRunner().run(suite)
    

    Using Python 3 to execute it, the following error is raised:

    Traceback (most recent call last):
      File "test.py", line 10, in <module>
        unittest.TextTestRunner().run(suite)
      File "/usr/lib/python3.2/unittest/runner.py", line 168, in run
        test(result)
      File "/usr/lib/python3.2/unittest/suite.py", line 67, in __call__
        return self.run(*args, **kwds)
      File "/usr/lib/python3.2/unittest/suite.py", line 105, in run
        test(result)
      File "/usr/lib/python3.2/unittest/case.py", line 477, in __call__
        return self.run(*args, **kwds)
      File "/usr/lib/python3.2/unittest/case.py", line 408, in run
        testMethod = getattr(self, self._testMethodName)
    AttributeError: 'Test' object has no attribute 'runTest'
    

    But unittest.main() works.