Python的单元测试逻辑

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

最佳答案

来自 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/

相关文章:

python - PyQt5多线程

python - 在 Postgresql 中将 CURRENT_DATE 设置为常量值以进行单元测试

java - 抽象类的 Jacoco 代码覆盖率部分显示

unit-testing - 用 Jest 模拟 redux saga 中间件

python - 这段 python 代码应该打印出一些信息,但没有

python - 如何在 PySpark 中只打印 DataFrame 的某一列?

python - 如何在 Python 2.7 中查找磁盘空间(不适用于 os.statvfs)

python - 当pandas中有混合列数据时添加条件滚动计数

unit-testing - Angular 返回模块中的测试服务未定义

unit-testing - 如何防止 Pester Mocked Read-Host 在代码覆盖期间提示输入