如何在python unittest中指定特定于测试的设置和拆卸
我想用两种不同的设置和拆卸方法在同一个类中用两种不同的测试创建unittest测试 每个测试都将在python unittest框架中使用其特定的设置和拆卸方法 谁能帮帮我吗如何在python unittest中指定特定于测试的设置和拆卸,python,python-unittest,nose2,Python,Python Unittest,Nose2,我想用两种不同的设置和拆卸方法在同一个类中用两种不同的测试创建unittest测试 每个测试都将在python unittest框架中使用其特定的设置和拆卸方法 谁能帮帮我吗 class processtestCase(unittest.TestCase): print "start the process test cases " def setUp1(self): unittest.TestCase.setUp(se
class processtestCase(unittest.TestCase):
print "start the process test cases "
def setUp1(self):
unittest.TestCase.setUp(self)
def test_test1(self):
"test Functinality"
def tearDown1(self):
unittest.TestCase.tearDown(self)
def setUp2(self):
unittest.TestCase.setUp2(self)
def test_test2(self):
"test Functinality"
def tearDown2(self):
unittest.TestCase.tearDown2(self) '
if __name__ == '__main__':
unittest.main()
在问题中,您提到有两个测试,每个测试都有自己的设置和拆卸。至少有两条路要走: 您可以将
设置
和拆卸
代码嵌入到每个测试中:
class FooTest(unittest.TestCase):
def test_0(self):
... # 1st setUp() code
try:
... # 1st test code
except:
... # 1st tearDown() code
raise
def test_1(self):
... # 2nd setUp() code
try:
... # 2nd test code
except:
... # 2nd tearDown() code
raise
或者,您可以将该类拆分为两个类:
class FooTest0(unittest.TestCase):
@classmethod
def setUp(cls):
...
@classmethod
def tearDown(cls):
...
def test(self):
...
第一个选项的类更少、更短、更直接。第二个选项更清晰地解耦了设置夹具和清理夹具,然后是测试代码本身。它还可以为未来添加更多的测试
您应该根据您的具体情况和个人偏好来判断权衡。在问题中,您提到您有两个测试,每个测试都有自己的设置和拆卸。至少有两条路要走: 您可以将
设置
和拆卸
代码嵌入到每个测试中:
class FooTest(unittest.TestCase):
def test_0(self):
... # 1st setUp() code
try:
... # 1st test code
except:
... # 1st tearDown() code
raise
def test_1(self):
... # 2nd setUp() code
try:
... # 2nd test code
except:
... # 2nd tearDown() code
raise
或者,您可以将该类拆分为两个类:
class FooTest0(unittest.TestCase):
@classmethod
def setUp(cls):
...
@classmethod
def tearDown(cls):
...
def test(self):
...
第一个选项的类更少、更短、更直接。第二个选项更清晰地解耦了设置夹具和清理夹具,然后是测试代码本身。它还可以为未来添加更多的测试
您应该根据您的具体情况和个人喜好来判断权衡。您能举一个您想要实现的目标的例子吗?如果测试需要单独的设置和拆卸,为什么它们在同一个类中?我们需要创建一组特定于功能的测试,这样我们就不需要为每个测试创建单独的类,但其中一些测试需要一些不同的设置,所以我需要为这些测试添加不同的设置和拆卸。就像java中的TestNg一样,我们可以在同一个类中提供多个testSetup,那么在python unittest中是否可能呢?这并不能回答我的任何一个问题。给出一些示例。示例“代码”类processtestCase(unittest.TestCase):打印“为摄取API启动流程测试用例”定义设置1(self):unittest.TestCase.setUp(self)def test_test1(self):“测试功能性”def tearDown1(self):unittest.TestCase.tearDown(self)def setUp2(self):unittest.TestCase.setUp2(self)def test_test2(self):“测试功能性”def tearDown2(self):unittest.TestCase.tearDown2(self)‘代码’哦,真可惜。。。这个问题!!你能举一个你想要达到的目标的例子吗?如果测试需要单独的设置和拆卸,为什么它们在同一个类中?我们需要创建一组特定于功能的测试,这样我们就不需要为每个测试创建单独的类,但其中一些测试需要一些不同的设置,所以我需要为这些测试添加不同的设置和拆卸。就像java中的TestNg一样,我们可以在同一个类中提供多个testSetup,那么在python unittest中是否可能呢?这并不能回答我的任何一个问题。给出一些示例。示例“代码”类processtestCase(unittest.TestCase):打印“为摄取API启动流程测试用例”定义设置1(self):unittest.TestCase.setUp(self)def test_test1(self):“测试功能性”def tearDown1(self):unittest.TestCase.tearDown(self)def setUp2(self):unittest.TestCase.setUp2(self)def test_test2(self):“测试功能性”def tearDown2(self):unittest.TestCase.tearDown2(self)‘代码’哦,真可惜。。。这个问题!!