首页 > 解决方案 > 为什么终端为我提供此 .py 脚本的零结果?

问题描述

我正在学习 unittest 并尝试处理以下两个 .py 脚本,但是当我在终端上运行时,它显示“运行 0 个测试”。我究竟做错了什么?

理智.py

def firstname(name):
    return name.title()

然后是第二个

sanitycheck.py

import unittest
import sanity

class TestingCap(unittest.TestCase):

    def firstone(self):
        word = 'apple'
        result = sanity.firstname(word)
        self.assertEqual(result,'apple')

if __name__ == '__main__':
    unittest.main()

谢谢!

标签: pythonunit-testing

解决方案


默认情况下,unittest 假定 a 中的测试unittest.TestCase是名称以“test_”开头的方法

将您的测试方法名称更改为“test_firstone”:

import unittest
import sanity

class TestingCap(unittest.TestCase):

    def test_firstone(self):
        word = 'apple'
        result = sanity.firstname(word)
        self.assertEqual(result,'apple')

if __name__ == '__main__':
    unittest.main()
python sanitycheck.py
F
======================================================================
FAIL: test_firstone (__main__.TestingCap)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "sanitycheck.py", line 9, in test_firstone
    self.assertEqual(result,'apple')
AssertionError: 'Apple' != 'apple'
- Apple
? ^
+ apple
? ^


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

如果你愿意,你可以改变 unittest 的行为。查看文档:https ://docs.python.org/3/library/unittest.html


推荐阅读