wonder
wonder

Reputation: 903

Python's unittest setUp function internal working

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()

Output : one failure and one success.

Does the setUp() loads a copy of every variable defined in it for every test case ?? If yes, How can I use setUp() to access variables globally??

Upvotes: 1

Views: 376

Answers (1)

minji
minji

Reputation: 512

setUp run each test method. if you want to run only once, use setUpClass

My English isn't good. so this link helps you

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()

Upvotes: 2

Related Questions