我有一个正在测试的类,它在 __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/