Python unittest - Ran 0 tests in 0.000s

Viewed 33790

So I want to do this code Kata for practice. I want to implement the kata with tdd in separate files:

The algorithm:

# stringcalculator.py  
def Add(string):
   return 1

and the tests:

# stringcalculator.spec.py 
from stringcalculator import Add
import unittest

class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

if __name__ == '__main__':
    unittest.main()

When running the testfile, I get:

Ran 0 tests in 0.000s

OK

It should return one failed test however. What do I miss here?

7 Answers

I had a similar problem. My root cause was that I had placed the execution block for unittest.main inside the Test class. This kept messaging RAN 0 tests. Moving it outside of class work.

if __name__ == '__main__':
    unittest.main()

Same symptoms, but different problem. Make sure you're not mixing up tabs and spaces for indentation. The problem may occur when you copy the code from an online resource and update it to your needs. Since tabs and spaces look very much alike in most editors, the test function may simply not be defined correctly.

In my case, I added __init__.py to the current test directory and the problem goes away.

class TestStringCalculator(unittest.TestCase):
    def add_returns_zero_for_emptyString(self):
        self.assertEqual(Add(' '), 0)

 if __name__ == '__main__':
     unittest.main()

After considering above two points in above written code, I got below error due to prefix space at line ( if __name__ == '__main__')

python3 test_flaskr.py 
  File "test_flaskr.py", line 66
    if __name__ == '__main__':
                             ^

Ensure that there is no prefix space and you need to write code at 1st column as below:

if __name__ == '__main__':
   unittest.main()

Do not define __init__; per that link, use def setUp(self) instead and unittest will call it. Also, do not define run; I renamed mine to _run and the problem finally went away.

Related