gpt4 book ai didi

Python的单元测试逻辑

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:58 25 4
gpt4 key购买 nike

谁能给我解释一下这个结果。第一个测试成功但第二个失败,尽管在第一个测试中测试的变量已更改。

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

最佳答案

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

When a setUp() method is defined, the test runner will run that method prior to each test.

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

关于Python的单元测试逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com