python - 如何替换单元测试中 __init__ 方法中的默认参数

标签 python

我有一个正在测试的类,它在 __init__ 中公开一个参数,仅供测试之用。看起来像这样

class MyClass(object):
  def __init__(self, start_time=None):
    if start_time is None:
      start_time = time.time()

在我的测试中,我想使用假时间传入 start_time,因此我首先在 setUp() 中获取时间,然后将其传递给每个测试方法。

class MyclassTest(TestCase):
  def setUp(self):
    self.fake_start_time = time.time()

  def test_one(self):
    x = MyClass(start_time=self.fake_start_time)
    ...

  def test_two(self):
    x = MyClass(start_time=self.fake_start_time)
    ...

所有这些都有效,但我想知道是否有一种方法可以避免在每个测试中编写 start_time=self.fake_start_time 。我可以以某种方式替换 setUp()__init__ 方法的默认参数吗?

我想出了一个丑陋的方法来做到这一点,但想知道是否有更标准的方法,可能基于mock.patch

最佳答案

setUp中创建该类的实例:

def setUp(self)
    self.fake_start_time = time.time()
    self.x = MyClass(start_time=self.fake_start_time)

关于python - 如何替换单元测试中 __init__ 方法中的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42080776/

相关文章:

使用来自多个列表的值的 Python 字符串格式

python - 我一直收到错误 'module' 对象没有属性 'init'

python - 在 Python 中将 RGB 图像转换为灰度图像

python - 正确完成所有操作后出现 Ngrok 错误 6022

python - 如何使用Python中的函数连续扩展列表?

python - 读取文件内容时出现奇怪的字符

python - 使用 Python 进行内联 CSV 文件编辑

python - Comint-Mode 有类似 eval-print-last-sexp 的功能吗?

python - 如何在保留冗余值的同时将元组列表转换为字典?

python - 如何在 pyspark 的 spark 中使用 "for"循环