Python logic unittest

Can someone explain this result to me. The first test succeeds, but the second fails, although the verified variable changes in the first test.

>>> class MyTest(unittest.TestCase):
    def setUp(self):
        self.i = 1
    def testA(self):
        self.i = 3
        self.assertEqual(self.i, 3)
    def testB(self):
        self.assertEqual(self.i, 3)


>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3

----------------------------------------------------------------------
Ran 2 tests in 0.016s
+3
source share
5 answers

Each test runs using a new instance of the MyTest class. This means that if you change yourself in one test, the changes are not transferred to other tests, since self will refer to another instance.

In addition, as others have pointed out, setUp is called before each test.

+9
source

From http://docs.python.org/lib/minimal-example.html :

When the setUp () method is defined, the test runner will run this method earlier for each test.

, setUp() testB, 1. , setUp() .

+11

, setUp

0

, . , , testA testB .

0

setUp, , , . , testB , 1, 3.

tearDown, . , , tearDown .

-1
source

Source: https://habr.com/ru/post/1696960/


All Articles