Python unittest - Ran 0 tests in 0.000s

拥有回忆 提交于 2020-05-09 19:25:16

问题


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


来源:https://stackoverflow.com/questions/43957860/python-unittest-ran-0-tests-in-0-000s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!