Python 单元测试设置函数

标签 python

我对 Python 比较陌生。根据unittest.setUp文档:

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.

我关于setUp的问题如下:

在我们的测试代码库中,我看到我们通过继承unittest.TestCase来自定义Python测试框架。最初,unittest.TestCase 的名称为 setUptearDown。在自定义类中,我们有 setUpTestCase拆解测试用例。所以每次都会调用这两个函数,而不是原来的对应函数。

我的问题是:

  1. 底层测试运行器如何调用这些 setUptearDown 函数?
  2. 是否要求那些用于设置测试用例的函数应以setUp 开头,用于拆除测试用例的函数应以tearDown 开头?或者它可以命名为任何有效的标识符?

谢谢。

最佳答案

  1. setUp() 和 tearDown() 方法在继承自 unittest.TestCase 的类中可用时会自动使用。
  2. 它们应该命名为 setUp() 和 tearDown(),只有在执行测试方法时才会使用它们。

例子:

class MyTestCase(unittest.TestCase):
  def setUp(self):
     self.setUpMyStuff()

  def tearDown(self):
     self.tearDownMyStuff()

class TestSpam(MyTestCase):
  def setUpMyStuff(self):
    # called before execution of every method named test_...
    self.cnx = # ... connect to database

  def tearDownMyStuff(self):
    # called after execution of every method named test_...
    self.cnx.close()

  def test_get_data(self):
    cur = self.cnx.cursor()
    ...

关于Python 单元测试设置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657543/

相关文章:

javascript - 在 Windows7 上安装 SRA-SiliconValley Jalangi 失败

python - 我陷入了 SKlearn 的属性错误

python - 需要创建一个新的 Python 列表,其中包含另一个列表的所有可能的唯一组合

javascript - 带有 JSON 数据的 D3 线,未渲染

python - 添加新行以计算现有 pandas 数据帧的总和和平均值

python - 如何为 Glass 设置目标位置?

python - 远程访问 MySql DB(托管选项)

python - 从字符串中删除字符的特定实例

python - 使用 Expect 在远程机器上运行本地 Python 脚本

python - 围绕水印opencv的轮廓