Python unittest - Ran 0 tests in 0.000s

2020-05-21 09:05发布

问题:

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?

回答1:

As stated in the python unittest doc:

The simplest TestCase subclass will simply implement a test method (i.e. a method whose name starts with test)

So you will need to change your method name to something like this:

def test_add_returns_zero_for_emptyString(self):
    self.assertEqual(Add(' '), 0)


回答2:

Sidenote: Also, the name of the file in which all the tests are there should start with 'test_'



回答3:

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.



回答4:

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()


回答5:

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()