python - Python 单元测试 - 为什么创建一个类?

标签 python testing

假设您正在使用 Python 中的单元测试框架编写单元测试。

我习惯于为每个测试使用类和各种方法来编写单元测试,例如如果你有一些函数cuboid_volume来计算立方体的体积:

def cuboid_volume(l):
    return (l*l*l)

然后您将按如下方式构建单元测试:

import unittest

class TestCuboid(unittest.TestCase):
    def test_volume(self):
      self.assertAlmostEqual(cuboid_volume(2),8)
    

但是,我也看到过一些示例,其中单元测试是在不使用类的情况下构建的。下面的例子:

def test_volume():
  assert cuboid_volume(2) == 8

我的问题是:这样做有什么好处以及为什么首先使用类?

最佳答案

使用类的好处

  1. 您可以从类unittest.TestCase调用继承的方法,这就是为什么您可以使用self.assertAlmostEqual
  2. 将相关测试用例分组到一个类中,以便它们可以在相关测试用例之间共享公共(public)数据/属性。每个测试方法也有相同的 setUptearDown 调用,或者每个类的 setUpClasstearDownClass

关于python - Python 单元测试 - 为什么创建一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71481401/

相关文章:

xml - 如何为 Spring 测试创建 TestContext?

java - mockito如何创建模拟对象的实例

javascript - Mocha 不会在 after() 函数中调用 rmdir

Python 正则表达式 : return the whole sentence with a certain word in it from period to period

python - 如何选择使用哪种字符编码?

python - 如何使用 beautifulSoup 从 <td> 标签中单独抓取数据?

python - 从 Sphinx autodoc 扩展中的文档中排除静态成员

iphone - 使用 iOS 7 beta 对 iOS 应用程序进行 Beta 测试

testing - Google Play - 应用内购买 - 测试人员未被告知他们不会被收费

python - Liskov 替换原则和 promise 对象