测试class

各种断言方法:

assertEqual(a,b)

   a == b

assertNotEqual(a,b)

   a != b

assertTrue(x)

 x == True

assertFalse(x)

 x == Flase

assertIn(item,list)

判断item 在 list中

assertNotIn(item,list)

判断 item不在list中

编写一个类,用于调查用户最喜欢的运动:

class Survey():
'''问卷调查'''
def __init__(self,question):
self.question = question
self.responses = []

def show_question(self):
'''显示问题'''
print(self.question)

def store_response(self,new_response):
'''存储单个答案'''
self.responses.append(new_response)

def show_results(self):
'''显示收集到的答案'''
print('surver_result :')
for response in self.responses:
print('- ' + response)

这个类,通过方法 show_question(),对用户进行提问;通过方法 store_response()来保存用户的答复。

最终生成一个列表:responses 用于包含用户的答案。

编写一个测试代码,对这个类进测试:

import unittest
from surveys import Survey

class Test_Survey(unittest.TestCase):
'''针对Survey进测试的类'''
def test_store_single_responses(self):
'''测试1个答案的方法'''
question = "What is your favorite sports ?"
my_survey = Survey(question)
my_survey.store_response('compute games')
self.assertIn('compute games' , my_survey.responses)

这个代码只能对一个答案进行测试,意义不大,如果用户输入了多个答案,如何确保程序不出错,也需要进行测试。
import unittest
from surveys import Survey

class Test_Survey(unittest.TestCase):
'''针对Survey进测试的类'''
def test_store_single_responses(self):
'''测试1个答案的方法'''
question = "What is your favorite sports ?"
my_survey = Survey(question)
my_survey.store_response('compute games')
self.assertIn('compute games' , my_survey.responses)
def test_store_more_response(self):
'''测试多个答案的方法'''
question = "What is your favorite sports ?"
my_survey = Survey(question)
responses = ['basketball' , 'football' , 'compute games']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response,my_survey.responses)

通过setUp巧妙的修改这个测试代码:

import unittest
from surveys import Survey

class Test_Survey(unittest.TestCase):
'''测试Survey类是否在各种情况正常工作'''

def setUp(self):
question = "What is your favorite sports ?"
self.my_survey = Survey(question)
self.responses = ['basketball' , 'football' , 'compute games']

def test_single_response(self):
'''测试单个答案的方法'''
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0],self.my_survey.responses)
def test_more_response(self):
'''测试多个答案的方法'''
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)


原文地址:https://www.cnblogs.com/alben-cisco/p/6864255.html