码迷,mamicode.com
首页 > 编程语言 > 详细

Python代码单元测试

时间:2019-10-20 19:37:17      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:sel   没有   first   blog   you   arm   ted   div   测试用例   

 

单元测试 用于核实函数的某个方面没有问题,测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求

  模块unittest提供了代码测试工具

测试函数

  用于测试的类必须继承unittest.TestCase类

  unittest类最有用的功能之一是:一个断言方法。断言方法用于核实得到的结果是否与期望的结果一致

name_function.py

def get_formatted_name(first, last):

   full_name = first + ‘ ‘ + last
return full_name.title()

test.py

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

 

#unittest.main() 使用pycharm不需要加这句

测试类

  unittest.TestCase类包含方法setUp( ), 可以让我们只需要创建测试中使用的对象一次,并在每个测试方法中使用它们。如果在TestCase中包含了方法setUp( ), Python将

先运行它,再运行各个以test_打头的方法。这样在每个测试方法中就都能使用在方法setUp( )中创建的对象了。

下面是书中测试类的一个例程:

survey.py

class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []

def store_response(self, new_response):
self.responses.append(new_response)

def show_results(self):
print("Survey results: ")
for response in self.responses:
print(‘- ‘ + response)

test_survey.py

import unittest
from survey import AnonymousSurvey


class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = [‘English‘, ‘Spanish‘, ‘Mandarin‘]

def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(‘English‘,self.my_survey.responses)

def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)

Python代码单元测试

标签:sel   没有   first   blog   you   arm   ted   div   测试用例   

原文地址:https://www.cnblogs.com/anthony-wang0228/p/11708570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!