assertRaises()
对 Python 类的 __init__()
方法进行单元测试?为了使用 assertRaises()
对 Python 类的 __init__()
方法进行单元测试,请按照以下步骤操作:
unittest.TestCase
的测试类。import unittest
class TestMyClass(unittest.TestCase):
pass
assertRaises()
函数对类的 __init__()
方法进行测试。import my_class
class TestMyClass(unittest.TestCase):
def test_init(self):
with self.assertRaises(TypeError):
my_class.MyClass()
assertRaises()
函数。class TestMyClass(unittest.TestCase):
def test_init(self):
with self.assertRaises(TypeError):
my_class.MyClass()
def test_init_with_valid_arguments(self):
my_class.MyClass(arg1=1, arg2=2)
unittest.main()
函数运行测试,并查看测试结果。if __name__ == '__main__':
unittest.main()
class MyClass:
def __init__(self, arg1=None, arg2=None):
if arg1 is None and arg2 is None:
raise TypeError('Both arguments must be provided')
self.arg1 = arg1
self.arg2 = arg2
# 创建测试类
import unittest
class TestMyClass(unittest.TestCase):
def test_init(self):
with self.assertRaises(TypeError):
my_class.MyClass()
def test_init_with_valid_arguments(self):
my_class.MyClass(arg1=1, arg2=2)
if __name__ == '__main__':
unittest.main()
通过使用 assertRaises()
函数,我们可以对 Python 类的 __init__()
方法进行单元测试。这种方法有助于确保类的初始化方法能够正确处理各种参数,并在出现错误时引发异常。
领取专属 10元无门槛券
手把手带您无忧上云