python-unittest

类的测试

import unittest导入unittest模块

定义一个继承自unittest.TestCase的测试用例类 class TestSurvey(unittest.TestCase)

unittest类包含方法setUp(),只需要创建一次对象,就可以在每个测试方法中使用它们

如果在TestCase类中包含了方法setUp(),python将先运行它,再运行各个以test_开头的方法,这样编写的每个测试方法中都可使用在setUp()中创建的对象了
定义测试用例,名字以test开头,unittest会自动将test开头的方法放入测试用例集中

调用unittest.main()启动测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
assertEqual(a, b)          a == b

assertNotEqual(a, b) a != b

assertTrue(x) bool(x) is True

assertFalse(x) bool(x) is False

assertIs(a, b) a is b

assertIsNot(a, b) a is not b

assertIsNone(x) x is None

assertIsNotNone(x) x is not None

assertIn(item, list) item in list

assertNotIn(item, list) item not in list

assertIsInstance(a, b) isinstance(a, b)

assertNotIsInstance(a, b) not isinstance(a, b)

类测试案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self, question):
"""存储一个问题,并为存储答案做准备"""

self.question = question
self.responses = []

def show_question(self):
# 显示调查问卷
print(self.question)

def store_responses(self, new_respones):
"""存储单份调查问卷"""
self.responses.append(new_respones)

def show_result(self):
"""显示收集到的所以信息"""
print("survey result:")
for response in self.responses:
print("- " + response)
print(self.responses)

关于survey的测试用例

test_survey.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import unittest
from survey import AnonymousSurvey

class TestSurvey(unittest.TestCase):
"""争对AnonymousSurvey类的测试"""
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):
"""测试单个答案存储"""
# question = "what language did you first learn to speak?"
# my_survey = AnonymousSurvey(question)
self.my_survey.store_responses(self.responses[1])

self.assertIn(self.responses[1], self.my_survey.responses)

def test_store_three_responses(self):
"""测试三个答案存储"""
# question = "what language did you first learn to speak?"
# my_survey = AnonymousSurvey(question)
# responses = ["English", "Spanish", "Mandarin"]
for response in self.responses:
self.my_survey.store_responses(response)

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


if __name__ == '__main__':
unittest.main()

测试效果