解释“设置"和“拆解"测试用例中使用的 Python 方法 [英] Explain the "setUp" and "tearDown" Python methods used in test cases

查看:30
本文介绍了解释“设置"和“拆解"测试用例中使用的 Python 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anyone explain the use of Python's setUp and tearDown methods while writing test cases apart from that setUp is called immediately before calling the test method and tearDown is called immediately after it has been called?

推荐答案

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

In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.

您可以在此处阅读更多示例.

You can read more with examples here.

当定义了 setUp() 方法时,测试运行器将运行该方法在每次测试之前.同样,如果定义了 tearDown() 方法,则测试运行器将在每次测试后调用该方法.

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.

For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.

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

Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.

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

So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.

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

You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.

如果您正在寻找一个简单的示例,请使用下面的示例链接

If you are looking for an easy example please use the following link with example

这篇关于解释“设置"和“拆解"测试用例中使用的 Python 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆