Python_unittest单元测试学习笔记
1.常用的几种断言函数:
序号 | 断言方法 | 断言描述 |
---|---|---|
1 | assertEqual(arg1, arg2, msg=None) | 验证arg1=arg2,不等则fail |
2 | assertNotEqual(arg1, arg2, msg=None) | 验证arg1 != arg2, 相等则fail |
3 | assertTrue(expr, msg=None) | 验证expr是true,如果为false,则fail |
4 | assertFalse(expr,msg=None) | 验证expr是false,如果为true,则fail |
5 | assertIs(arg1, arg2, msg=None) | 验证arg1、arg2是同一个对象,不是则fail |
6 | assertIsNot(arg1, arg2, msg=None) | 验证arg1、arg2不是同一个对象,是则fail |
7 | assertIsNone(expr, msg=None) | 验证expr是None,不是则fail |
8 | assertIsNotNone(expr, msg=None) | 验证expr不是None,是则fail |
9 | assertIn(arg1, arg2, msg=None) | 验证arg1是arg2的子串,不是则fail |
10 | assertNotIn(arg1, arg2, msg=None) | 验证arg1不是arg2的子串,是则fail |
11 | assertIsInstance(obj, cls, msg=None) | 验证obj是cls的实例,不是则fail |
12 | assertNotIsInstance(obj, cls, msg=None) | 验证obj不是cls的实例,是则fail |
13 | assertRaises(expr) |
验证expr异常类型,结合with使用 例子: with self.assertRaises(Exception): # 测试内容 |
2.测试之前和之后运行的函数方法。
模块级别:在一个py文件中的所有测试的开始和结束执行
def setUpModule(): print("-----------1") def tearDownModule(): print("===========2")
类级别:在一个类里面的所有测试的开始和结束执行
class TestMyService(unittest.TestCase): @classmethod def setUpClass(cls): print("----------1") @classmethod def tearDownClass(cls): print("----------2")
方法级别:在类的每一个测试的开始和结束执行
class TestMyService(unittest.TestCase): def setUp(self): print("----------111") def tearDown(self): print("----------222")
3.Mock(模拟)
1.要测试的demo
class Student(object): def __init__(self, id, name): self.id = id self.name = name
def find_student_by_id(id): return Student(1, "wdc") def save_student(student): pass def change_name(student_id, name): student = find_student_by_id(student_id) if student is not None: student.name = name save_student(student)
2.只用Mock测试
import unittest from unittest.mock import Mock from commons import demo03 class TestDemo03(unittest.TestCase): def test_change_name(self): # setUp demo03.find_student_by_id = Mock() temp_var = Mock(id=1, name="wdc") demo03.find_student_by_id.return_value = temp_var demo03.save_student = Mock() # action demo03.change_name(1, "yhf") # assert self.assertEqual("yhf", temp_var.name) demo03.save_student.assert_called() def test_change_name_without_record(self): # setUp demo03.find_student_by_id = Mock() # temp_var = Mock(id=1, name="wdc") demo03.find_student_by_id.return_value = None demo03.save_student = Mock() # action demo03.change_name(1, "yhf") # assert demo03.save_student.assert_not_called()
3.patch
import unittest from unittest.mock import Mock, patch from commons import demo03 class TestDemo03(unittest.TestCase): @patch("commons.demo03.save_student") @patch("commons.demo03.find_student_by_id") def test_change_name(self, find_student_by_id_mock, save_student_mock): # setUp temp_var = Mock(id=1, name="wdc") find_student_by_id_mock.return_value = temp_var # action demo03.change_name(1, "yhf") # assert self.assertEqual("yhf", temp_var.name) demo03.save_student.assert_called()