Python的单元测试逻辑

mbe*_*sso 3 python unit-testing

有人可以向我解释这个结果.第一次测试成功但第二次测试失败,尽管测试的变量在第一次测试中发生了变化.

>>> 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
Run Code Online (Sandbox Code Playgroud)

pjz*_*pjz 11

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

定义setUp()方法时,测试运行器将在每次测试之前运行该方法.

因此setUp()在testA和testB之前运行,每次都将i设置为1.在幕后,整个测试对象实际上正在为每个测试重新实例化,在执行测试之前,每个新的实例化都会运行setUp().


Seb*_*tau 9

每个测试都使用MyTest类的新实例运行.这意味着如果您在一次测试中更改self,则更改将不会转移到其他测试,因为self将引用其他实例.

此外,正如其他人所指出的那样,在每次测试之前调用setUp.