[英]Execution order on Python unittest
I need to set an order of execution for my tests, because I need some data verified before the others.我需要为我的测试设置执行顺序,因为我需要在其他数据之前验证一些数据。 Is possible to set an order?
可以设置订单吗?
class OneTestCase(unittest.TestCase):
def setUp(self):
# something to do
def test_login (self):
# first test
pass
def test_other (self):
# any order after test_login
def test_othermore (self):
# any order after test_login
if __name__ == '__main__':
unittest.main()
You can do it like this:你可以这样做:
class OneTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# something to do
pass
def test_01_login (self):
# first test
pass
def test_02_other (self):
# any order after test_login
def test_03_othermore (self):
# any order after test_login
if __name__ == '__main__':
unittest.main(failfast=True, exit=False)
Tests are sorted alphabetically, so just add numbers to get your desired order.测试按字母顺序排序,因此只需添加数字即可获得所需的顺序。 Probably you also want to set
failfast = True
for the testrunner, so it fails instantly, as soon as the first test fails.可能您还想为 testrunner 设置
failfast = True
,因此一旦第一个测试失败,它就会立即失败。
Better do not do it.最好不要这样做。
Tests should be independent.测试应该是独立的。
To do what you want best would be to put the code into functions that are called by the test.做你最想做的事是将代码放入测试调用的函数中。
Like that:像那样:
def assert_can_log_in(self):
...
def test_1(self):
self.assert_can_log_in()
...
def test_2(self):
self.assert_can_log_in()
...
Or even to split the test class and put the assertions into the setUp function.甚至可以拆分测试类并将断言放入 setUp 函数中。
class LoggedInTests(unittest.TestCase):
def setUp(self):
# test for login or not - your decision
def test_1(self):
...
When I split the class I often write more and better tests because the tests are split up and I can see better through all the cases that should be tested.当我拆分班级时,我经常编写更多更好的测试,因为测试是分开的,我可以更好地了解所有应该测试的案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.