Python的unittest setUp函数内部工作

时间:2017-04-28 03:33:24

标签: python python-unittest

import unittest

class TestString(unittest.TestCase):

    def setUp(self):
        self.subject_list = ["Maths","Physics","Chemistry"]

    def test_student_1(self):
        self.assertListEqual(self.subject_list,["Maths","Physics","Chemistry"])
        self.subject_list.remove("Maths")

    def test_student_2(self):
        self.assertListEqual(self.subject_list,["Physics","Chemistry"])

if __name__ == "__main__":
    unittest.main()

输出:一次失败,一次成功。

setUp()是否为每个测试用例加载了为其定义的每个变量的副本?如果是,我如何使用setUp()全局访问变量?

1 个答案:

答案 0 :(得分:1)

setUp运行每个测试方法。如果您只想运行一次,请使用setUpClass

我的英语不好。所以link可以帮助你

import unittest


class TestString(unittest.TestCase):
    subject_list = ["Maths", "Physics", "Chemistry"]

    def test_student_1(self):
        self.assertListEqual(self.subject_list, ["Maths", "Physics", "Chemistry"])
        self.subject_list.remove("Maths")

    def test_student_2(self):
        self.assertListEqual(self.subject_list, ["Physics", "Chemistry"])


if __name__ == "__main__":
    unittest.main()