运行unittest.main()时“没有找到测试”

问题描述 投票:1回答:2

我有一个测试文件和一个主模块文件,其中有一个我正在测试的功能。在我的测试文件的末尾,我有unittest.main()来运行单元测试。但是,当我运行测试文件时,控制台显示“没有找到测试”,即使我的文件中有2个单元测试(参见下面的截图和最后的源代码)。 No tests were found Pycharm当我:这个问题似乎消失了:

(1)将unittest.main()包含在if __name__ == "__main__"中(切线:我理解这个子句是如何工作的,但是在这种情况下,当unittest.main()模块在有if子句时正常运行时,对比我没有意义,相比之下没有任何条件所有),或

(2)当我在Spyder中运行我的测试程序时(我目前正在使用Pycharm)

因此,我不太确定这是我的IDE或我的代码特有的问题。我从这个问答环节尝试了recommended fix,但都没有奏效。如果您对我应该做什么/配置让unittest.main正常运行有任何想法,我真的很感激!


供您参考,以下是我程序中的2个文件;我的测试文件没有返回测试,而不是我为它编写的2个测试。

---主文件:city_functions.py ---

def print_city_country(city, country, population=""):
    """Print 'city, country' from input city and country"""
    if population:
        formatted_city_country = city + ", " + country + " - population " + str(population)
    else:
        formatted_city_country = city + ", " + country
    return formatted_city_country

---测试文件:test_cities.py ---

import unittest
from city_functions import print_city_country


class TestCaseCityCountry(unittest.TestCase):
    """Test function city_country from city_functions module"""

    def test_city_country_pair(self):
        """Test for names like Santiago, Chile without population input"""
        formatted_city_country = print_city_country("Santiago", "Chile")
        self.assertEqual(formatted_city_country, "Santiago, Chile")

    def test_city_country_population(self):
        """Test for names like Santiago, Chile, 5000000"""
        formatted_city_country_population = print_city_country("Santiago", "Chile", 5000000)
        self.assertEqual(formatted_city_country_population, "Santiago, Chile - population 5000000")


unittest.main()
python python-3.x unit-testing pycharm
2个回答
1
投票

作为使用Pycharm的初学者,Don Kirkby的answer对我帮助最大。

解决方案,至少对我来说只是简单地从文件中删除unittest.main()。每当测试运行时,Pycharm默认使用命令python -m unittest,并且unittest.main()方法会弄乱语法。

我希望这可以帮助那些来到这里遇到同样问题的人。


0
投票

有两种方法可以启动unittest测试。一个是你正在使用的unittest.main()方法,但我总是使用command-line interfacepython -m unittest discover命令将在一堆文件中找到测试并将它们一起运行。

我不确定为什么unittest.main()不适合你,但无论如何我建议使用其他方法。

© www.soinside.com 2019 - 2024. All rights reserved.