Python 中 unittest 的一个误会...

本文解析了unittest框架中setUp与tearDown方法的作用及调用时机。它们并非针对整个测试类,而是在每个测试方法前后分别调用,用于准备和清理测试环境。

一直以为 TestCase 中的 setUp( ) 与 tearDown( )  是针对 整个TestCase 的

昨天 偶然发现 原来不是这个样子.这两个方法都是在每个测试方法先后调用,帮助上是这么写的
setUp( )

Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.

tearDown( )

Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.

相关代码如下,TestCase 中的__Call__


    def __call__(self, result=None):
        if result is None: result = self.defaultTestResult()
        result.startTest(self)
        testMethod = getattr(self, self.__testMethodName)
        try:
            try:
                self.setUp()
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self.__exc_info())
                return

            ok = 0
            try:
                testMethod()
                ok = 1
            except self.failureException:
                result.addFailure(self, self.__exc_info())
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self.__exc_info())

            try:
                self.tearDown()
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self.__exc_info())
                ok = 0
            if ok: result.addSuccess(self)
        finally:
            result.stopTest(self)


### 如何在 Python 中通过命令行运行 unittest #### 使用 `unittest` 命令运行单个测试文件 当有一个特定的测试文件,比如 `test_calculator.py`,可以使用如下命令来执行其中所有的测试用例[^1]: ```bash python -m unittest test_calculator.py ``` 此方式适用于已知确切路径和名称的情况。 #### 发现并运行多个测试文件 对于项目中有多个测试文件存放在名为tests的目录下时, 可以让工具自动查找这些测试文件并通过下面这条指令一次性全部跑完它们[^2]: ```bash python -m unittest discover tests ``` 这会递归地搜索指定目录内的所有匹配模式 (默认为 "test*.py") 的文件作为测试套件的一部分. #### 运行模块、类或单独的方法级别的测试 如果目标更加具体,则可以选择只针对某个模块里的某一个类别甚至更细粒度至单一函数来进行验证工作。例如: - 整个模块:`test_module` ```bash python -m unittest test_module ``` - 特定类:`TestClass` 下的所有方法 ```bash python -m unittest test_module.TestClass ``` - 单独的一个测试方法:`test_method` ```bash python -m unittest test_module.TestClass.test_method ``` 以上三种情况分别对应着不同层次上的聚焦程度调整[^3]. #### 执行包含 `unittest.main()` 的脚本 另一种常见的做法是在编写好的测试代码里加入 `if __name__ == '__main__': unittest.main()` 结构,在这种情况下只需要像平常那样启动该 `.py` 文件即可触发内部定义好一切必要的逻辑流程[^5]: 假设存在这样一个简单的例子: ```python import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) if __name__ == '__main__': unittest.main() ``` 那么就可以简单地这样做去激活它所携带的功能集了: ```bash python script.py ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值