【问题标题】:PyCharm doesn't appear to run all unit testsPyCharm 似乎没有运行所有单元测试
【发布时间】:2017-04-20 07:47:56
【问题描述】:

我在 pycharm 中运行单元测试时遇到问题。第一个类“KnownValues”运行,但另一个类根本没有得到检查。

import roman
import unittest

class KnownValues(unittest.TestCase):

    def test_too_large(self):
        '''to_roman should fail with large input'''
        self.assertRaises(roman.OutOfRangeError, roman.to_roman, 4000)
    def test_too_small(self):
        ls = [0,-1,-25,-60]
        for x in ls:
            self.assertRaises(roman.OutOfRangeError, roman.to_roman, x)
    def test_non_int(self):
        ls = [1.5, -6.5, 6.8,12.9, "hello wold", "nigga123"]
        for x in ls:
             self.assertRaises(roman.TypeError, roman.to_roman, x)

class Test2(unittest.TestCase):
    def test1(self):
        assert 1 == 1


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

【问题讨论】:

  • 您是否确认这与您在 PyCharm 之外运行程序时的行为不同?
  • 如果将测试方法的名称从 test1 更改为 test_1 会怎样?
  • @Charlie no for pycharm 即使我将其更改为 test_1 也不会运行它
  • @holdenweb 是的,当我从 cmd 运行它时,它确实是 test_non_int (__main__.KnownValues) ... ok test_to_roman_known_values (__main__.KnownValues) to_roman should give known result with known input ... ok test_too_large (__main__.KnownValues) to_roman should fail with large input ... ok test_too_small (__main__.KnownValues) ... ok **test_1 (__main__.Test2) ... ok** -------------------------------------------------------------------- Ran 5 tests in 0.000s
  • 确保单击单元测试查看器工具栏上的绿色小圆圈,默认情况下它会隐藏通过的测试。

标签: python unit-testing class pycharm live-unit-tests


【解决方案1】:

使用test 启动所有测试功能。很多人使用下划线来分隔单词,所以很多人最终会使用test_ 开头的测试,但test 就足够了。

当 GUI 出现问题时,您可以从命令行检查测试的运行情况。

python test.py

python -m test

您可能遇到的一个问题是您已经在类中定义了测试,当通过 GUI 运行它们时,GUI 会自动为您发现它们。确保在测试文件末尾包含指示解释器使用 unittest 内置的 main 函数的行。

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

请记住,您可以选择一次只在一个类中运行测试:

python tests.py KnownValues
python tests.py Test2

在 PyCharm 中,它应该自动发现所有的测试类。您仍然可以选择一次只运行一门课程。选择 Run->Edit Configurations 以查看您当前正在运行的选项。使用命令行参数,您可以控制运行更少或更多的测试。

如您所见,您可以选择运行脚本、类或方法。请务必设置运行配置的名称,使其反映您正在运行的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多