运行 来自 main() 的 Python 中的特定单元测试

Run a specific unit tests in Python from main()

我正在尝试 运行 仅 class 中提供的单元测试中的一个测试。所以假设

class MytestSuite(unittest.TestCase):
    def test_false(self):
        a = False
        self.assertFalse(a, "Its false")

    def test_true(self):
        a = True
        self.assertTrue(a, "Its true")

我只想运行 test_false。根据本网站和在线提供的问答,我在我的主要 class

中使用了以下代码行
if __name__ == "__main__":  # Indentation was wrong
    singletest = unittest.TestSuite()
    singletest.addTest(MytestSuite().test_false)
    unittest.TextTestRunner().run(singletest)

我在尝试添加测试时不断遇到错误。主要是:

File "C:\Python27\Lib\unittest\case.py", line 189, in init
(self.class, methodName))
ValueError: no such test method in <class 'main.MytestSuite'>: runTest

我的 class 中是否需要特定的 运行 测试方法?有没有办法 运行 属于不同套件的特定测试?例如,方法 A 属于 套件 class 1方法 B 属于 套房class 2。令人惊讶的是,事实证明这很难在网上找到。有多个通过命令行执行此操作的示例,但不是来自程序本身。

您只是将错误的内容传递给了 addTest。您需要传递 TestCase 的新实例(在您的情况下是 MyTestSuite 的实例),而不是传入绑定方法,该实例由 name 构造您想要的单个测试 运行.

singletest.addTest(MyTestSuite('test_false'))

The documentation 有大量关于此的附加信息和示例。