1 import unittest 2 from name_func import get_name 3 4 class NamesTestCase(unittest.TestCase): 5 def test_first_last_name(self): 6 name = get_name('janis', 'joplin') 7 self.assertEqual(name, 'Janis Joplin') 8 9 unittest.main()
运行结果
. ---------------------------------------------------------------------- Ran 1 test in 0.014s OK
def test_first_last_name(self): name = get_name('janis', 'joplin', 'abc') self.assertEqual(name, 'Janis Joplin Abc')
运行结果
E ====================================================================== ERROR: test_first_last_name (__main__.NamesTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\Python\codes\7-24-01.py", line 6, in test_first_last_name name = get_name('janis', 'joplin', 'abc') TypeError: get_name() takes 2 positional arguments but 3 were given ---------------------------------------------------------------------- Ran 1 test in 0.009s FAILED (errors=1)
class AnonymousSurvey(): '''收集匿名调查问卷的答案''' def __init__(self, question): '''存储一个问题,并为存储答案做准备''' self.question = question self.responses = [] def store_response(self, new_resp): '''存储单份调查答卷''' self.responses.append(new_resp)
import unittest from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase): '''针对AnonymouSuvey类的测试''' def test_store_single_response(self): '''测试单个答案的存储''' question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) my_survey.store_response('English') self.assertIn('English', my_survey.responses) def test_store_three_response(self): '''测试三个答案的存储''' question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) responses = ['English', 'Spanish', 'Chinese'] for response in responses: my_survey.store_response(response) for response in responses: self.assertIn(response, my_survey.responses) unittest.main()
运行结果
.. ---------------------------------------------------------------------- Ran 2 tests in 0.012s OK
class TestAnonymousSurvey(unittest.TestCase): '''针对AnonymouSuvey类的测试''' def setUp(self): '''创建一个调查对象和一组答案,供测试方法使用''' question = "What language did you first learn to speak?" self.my_survey = AnonymousSurvey(question) self.responses = ['English', 'Spanish', 'Chinese'] def test_store_single_response(self): self.my_survey.store_response(self.responses[0]) self.assertIn(self.responses[0], 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) unittest.main()
运行结果
.. ---------------------------------------------------------------------- Ran 2 tests in 0.012s OK