# 以下是需要测试的类文件: Survey class Survey(object): """收集调查问卷""" def __init__(self, question): self.question = question self.respond =[] def show_question(self): """显示问题""" print(self.question) def store_respond(self, new_respond): self.respond.append(new_respond) def show_result(self): """显示收集的反馈信息""" for i in self.respond: print("-"+i)
-------------------------------------
针对上述类,编写单元测试用例-函数
# TDD: # # 问题1: 你的年纪是多少? # 回答1: 18岁 # # 问题1: 你的年纪是多少? # 回答1: 18岁, 19岁, 20岁 #导入需要测试的类文件 from survey import Survey #编写测试类: class TestSurvey(object): def test_one_respond(self): question = "你的年纪是多少?" a1 = Survey(question) a1.show_question() a1.store_respond(18) assert a1.respond[0] == 18 def test_three_respond(self): question = "你的年纪是多少?" a1 = Survey(question) a1.show_question() respond_list = [18, 19, 20] for i in respond_list: a1.store_respond(i) assert i in a1.respond print(a1.respond)
--------------执行结果如下-------------------
E:\python\python.exe "D:\JetBrains\PyCharm 2022.1.3\plugins\python\helpers\pycharm\_jb_pytest_runner.py" --target test_survey.py::TestSurvey
Testing started at 15:24 ...
Launching pytest with arguments test_survey.py::TestSurvey --no-header --no-summary -q in E:\learnPython\01_01_单元测试_实践
E:\python\Lib\site-packages\pep8.py:110: FutureWarning: Possible nested set at position 1
EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
============================= test session starts =============================
collecting ... collected 2 items
test_survey.py::TestSurvey::test_one_respond PASSED [ 50%]你的年纪是多少?
test_survey.py::TestSurvey::test_three_respond PASSED [100%]你的年纪是多少?
[18]
[18, 19]
[18, 19, 20]
============================== 2 passed in 0.02s ==============================
Process finished with exit code 0