我正在尝试使用不同的setUp方法运行相同的测试用例。我尝试过使用nosetests并参数化,但似乎它不支持参数化setUp方法。这是我正在尝试做的一个例子:
...
from nose_parameterized import parameterized
class Example(unittest.TestCase):
@parameterized.expand(['device1', 'device2'])
def setUp(self, device):
desired_caps = {}
desired_caps['key1'] = device
desired_caps['key2'] = 'constant value'
self.driver = webdriver.Remote(url, desired_caps)
def tearDown(self):
self.driver.quit()
def test_app_launch(self):
# assert something
错误是:TypeError: setUp() takes exactly 2 arguments (1 given)
。
有没有其他方法如何参数化setUp方法?我也研究了测鼻仪发生器,但它似乎也没办法。
答案 0 :(得分:1)
使用类属性:
class Example(unittest.TestCase):
# change before running tests
device = None
# make sure device is initialized
def setUpClass(cls):
if not cls.device:
raise Exception("Please initialize device before running tests")
def setUp(self):
# consider moving to 'setUpClass'
desired_caps = {}
desired_caps['key1'] = Example.device
desired_caps['key2'] = 'constant value'
self.driver = webdriver.Remote(url, desired_caps)
def tearDown(self):
self.driver.quit()
def test_app_launch(self):
# assert something
分别对每个设备运行测试。您的代码建议可以将更多内容移动到setUpClass
方法。
答案 1 :(得分:1)
所以我的方法是设置一个基本测试,其中包含设备必须通过的所有测试。然后你必须使用他们自己的附加setUps从deviceTest继承的deviceTests,这将是特定于设备的。
# this is the base test. Everything that is not specific to the device is set up here. It also contains all the testCases.
import unittest
class deviceTest( unittest.TestCase ):
def setUp( self ):
'''
General setUp here
'''
self.desired_caps = {}
self.desired_caps['key2'] = 'constant value'
def testWorkflow( self ):
'''
Here come the tests that the devices have to pass
'''
class device1Test( deviceTest ):
def setUp( self ):
'''
device1 specific setup
'''
#also run general setUp
deviceTest.setUp( self )
self.desired_caps['key1'] = device
self.driver = webdriver.Remote(url, desired_caps)
class device2Test( deviceTest ):
def setUp( self ):
'''
device2 specific setup
'''
#also run general setUp
deviceTest.setUp( self )
self.desired_caps['key1'] = device
self.driver = webdriver.Remote(url, desired_caps)
if __name__ == '__main__':
suite = unittest.defaultTestLoader.loadTestsFromTestCase( device1Test )
suite.addTest( unittest.defaultTestLoader.loadTestsFromTestCase(device2Test ) )
unittest.TextTestRunner( verbosity = 2 ).run( suite )
答案 2 :(得分:-1)
我只是在测试中使用参数化插件,并调出自定义设置和拆解方法,将设备参数作为测试的一部分传递给它们。使用unittest的setUp()
几乎没有什么魔力,看起来你无论如何都在滥用它。