测试函数是用于自动化测试,使用python模块中的unittest中的工具来测试
附上书中摘抄来的代码:
-
#coding=utf-8
-
import unittest
-
from name_function import get_formatted_name
-
-
class NamesTestCase(unittest.TestCase):
-
def test_first_last_name(self):
-
formatted_name=get_formatted_name( 'janis', 'joplin')
-
self.assertEqual(formatted_name, 'Janis Joplin')
-
-
def test_first_last_middle_name(self):
-
formatted_name=get_formatted_name( 'wolfgang', 'mozart', 'amadeus')
-
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
-
#注意下面这行代码,不写会报错哦~~~书中没有这行
-
if __name__== "__main__":
-
unittest.main()
需要注意的点:
让python运行测试代码,需要使用
unittest.main()
在此前面一定要加上
if __name__=="__main__":
否则会出现如下报错
Test framework quit unexpected
AttributeError: 'module' object has no attribute 'J:\Python\test_name_function'
正确代码运行结果:
以上的All 2 tests passed,表示此代码中有两个方法测试通过(test_first_last_name和test_first_last_middle_name)
在命令行运行时:
第一行的..表示两个测试通过,第二个行运行两个测试消费时间0.001s,最后的OK表示测试用例中的所有单元测试都通过。
注意注意:
测试方法名(本例是(test_first_last_name和test_first_last_middle_name))必须以test开头,否则这个python运行时不会自动运行测试方法。
转载自:https://blog.csdn.net/waiwai3/article/details/77513007