Python學習——代碼測試


單元測試 用於核實函數的某個方面沒有問題,測試用例是一組單元測試,這些單元測試一起核實函數在各種情形下的行為都符合要求

  模塊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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM