简体   繁体   English

Python的unittest框架TestCase很好奇

[英]Python's unittest framework TestCase curiousity

I'm trying to run a TestCase in python 3.3.2 that has several test methods in it: 我正在尝试在python 3.3.2中运行一个TestCase,它有几个测试方法:

class ttt(unittest.TestCase):
    def setUp(self):
        ...

    def tearDown(self):
        ...

    def test_test1(self):
        ...      

    def test_test2(self):
        ...



if __name__ == "__main__":
    instance = ttt()
    instance.run()

The documentation states the following: 文档说明如下:

Each instance of TestCase will run a single base method: the method named methodName. 每个TestCase实例都将运行一个基本方法:名为methodName的方法。 However, the standard implementation of the default methodName, runTest(), will run every method starting with test as an individual test, and count successes and failures accordingly. 但是,默认methodName,runTest()的标准实现将以test作为单独测试开始运行每个方法,并相应地计算成功和失败。 Therefore, in most uses of TestCase, you will neither change the methodName nor reimplement the default runTest() method. 因此,在TestCase的大多数用法中,既不会更改methodName,也不会重新实现默认的runTest()方法。

However, when I run the code I get the following: 但是,当我运行代码时,我得到以下内容:

'ttt' object has no attribute 'runTest'

I want to ask: Is this a bug? 我想问:这是一个错误吗? And if it's not why is there no runTest method? 如果不是为什么没有runTest方法呢? Am I doing something wrong? 难道我做错了什么?

When the unit test framework runs test cases, it creates an instance of the test class for each test. 当单元测试框架运行测试用例时,它会为每个测试创建一个测试类的实例。

Ie to simulate what the unit test framework does you need to do: 即模拟单元测试框架需要做什么:

if __name__ == "__main__":
    for testname in ["test_test1", "test_test2"]:
        instance = ttt(testname)
        instance.run()

The correct way to run unit tests in a module is: 在模块中运行单元测试的正确方法是:

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

... but I assume you know this already. ......但我猜你已经知道了。

Regarding runTest : unittest.TestCase.__init__ signature and docstring is: 关于runTestunittest.TestCase.__init__签名和docstring是:

def __init__(self, methodName='runTest'):
    """Create an instance of the class that will use the named test
       method when executed. Raises a ValueError if the instance does
       not have a method with the specified name.
    """

Meaning that if you don't specify a test name in the constructor, the default is runTest . 这意味着如果未在构造函数中指定测试名称,则默认为runTest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM