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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| import unittest from common import logger from student import Student from unittest.mock import Mock, create_autospec
class StudentTest(unittest.TestCase): logger = logger counter = 0
@classmethod def setUpClass(cls): cls.logger.info("Mock测试开始")
@classmethod def tearDownClass(cls): cls.logger.info("Mock测试结束")
def setUp(self): StudentTest.counter += 1 self.logger.info(f"用例-{StudentTest.counter}开始测试")
def tearDown(self): self.logger.info(f"用例-{StudentTest.counter}结束测试")
def test_get_name_1(self): s = Student()
print(s.get_name("刘", "一"))
s.get_name = Mock(return_value="陈二")
self.assertEqual(s.get_name(), "陈二") self.assertEqual(s.get_name("1"), "陈二") self.assertEqual(s.get_name("1", "2"), "陈二") self.assertEqual(s.get_name("1", "2", "3"), "陈二")
def test_get_name_2(self): s = create_autospec(Student)
self.assertEqual(s.get_name.call_count, 0) print(s.get_name("陈", "二")) self.assertEqual(s.get_name.call_count, 1) s.get_name.assert_called_with("陈", "二")
def test_get_name_3(self): s = Student()
s.get_name = create_autospec(s.get_name, return_value="张 三") self.assertEqual(s.get_name("1", "2"), "张 三")
def test_get_name_4(self): s = Student()
values = {("李", "四"): "李 四", ("王", "五"): "王 五"} s.get_name = Mock(side_effect=lambda x, y: values[(x, y)]) self.assertEqual(s.get_name("李", "四"), "李 四") self.assertEqual(s.get_name("王", "五"), "王 五")
def test_get_age_1(self): s = Student()
self.assertEqual(s.get_age(), 20) s.get_age = Mock(return_value=21) self.assertEqual(s.get_age(), 21)
def test_get_age_2(self): s = Student()
list = [27, 28, 29] s.get_age = Mock(return_value=20, side_effect=list) self.assertEqual(s.get_age(), 27) self.assertEqual(s.get_age(), 28) self.assertEqual(s.get_age(), 29)
|