python - 解释测试用例中使用的 "setUp"和 "tearDown"Python方法

标签 python unit-testing python-unittest

任何人都可以在编写测试用例时解释 Python 的 setUptearDown 方法的使用,除了在调用测试之前立即调用 setUp方法和 tearDown 在被调用后立即被调用?

最佳答案

通常,您将所有先决步骤添加到 setUp,并将所有清理步骤添加到 tearDown。

您可以阅读更多示例 here .

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.

例如,您有一个测试需要项目存在或特定状态 - 所以您将这些操作(创建对象实例、初始化数据库、准备规则等)放入 setUp。

你也知道每个测试应该在它开始的地方停止 - 这意味着我们必须将应用程序状态恢复到它的初始状态 - 例如关闭文件、连接、删除新创建的项目、调用事务回调等等- 所有这些步骤都将包含在tearDown中。

所以这个想法是测试本身应该只包含要在测试对象上执行以获得结果的操作,而 setUp 和 tearDown 是帮助您保持测试代码干净和灵活的方法。

您可以为一堆测试创建 setUp 和 tearDown 并在父类中定义它们 - 这样您就可以轻松支持此类测试并更新常见的准备和清理。

如果您正在寻找一个简单的示例,请 use the following link with example

关于python - 解释测试用例中使用的 "setUp"和 "tearDown"Python方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6854658/

相关文章:

Python 枚举 : How to get enum values with multiple attributes

python - 如何在 python 中将时间 "now-5m"转换为 datetime 对象

python - uwsgi + Flask + virtualenv ImportError : no module named site

unit-testing - 如何使用 gomock (或类似的)来模拟/验证对数据库的调用?

python pytest 偶尔会因 OSError : reading from stdin while output is captured 而失败

python - 为 Tkinter Scale 小部件设置 `orient` 关键字参数会导致 NameError : name 'HORIZONTAL' is not defined

PHPUnit 使用注解断言异常与方法调用

c# - MS 测试断言检查

python - 当测试一起运行时,所有测试中使用的外部库模拟补丁不起作用

python - 如何使用 moto @mock_dynamodb2 模拟失败的操作?