38

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.

Jingguo Yao
  • 7,320
  • 6
  • 50
  • 63

4 Answers4

47

You need to invoke a TestLoader:

if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test)
    unittest.TextTestRunner().run(suite)
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
15

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()
falsetru
  • 357,413
  • 63
  • 732
  • 636
-1

The actual test for any TestCase subclass is performed in the runTest() method. Simply change your code to:

class Test(unittest.TestCase):
    def runTest(self):
        assert(True == True)
Sajjan Singh
  • 2,523
  • 2
  • 27
  • 34
  • 1
    Yes, it works. But is there a way to make it work without changing the Test class? @bhajun-singh. – Jingguo Yao Sep 30 '13 at 06:30
  • 1
    Just say `pass` instead of `assert(True == True)` – Adrian W Mar 30 '17 at 18:20
  • This [documentation](https://docs.python.org/3/library/unittest.html) seems to say otherwise. To wit: "Each instance of TestCase will run a single base method: the method named methodName. In most uses of TestCase, you will neither change the methodName nor reimplement the default runTest() method." – N6151H Aug 01 '19 at 09:08
-1

You can run it like this:

python -m unittest <your-module-name>

I don't fully understand why it works though.

Kent Tong
  • 87
  • 4