在测试方法中需要判断结果是pass还是fail,自动化测试脚本里面一般把这种生成测试结果的方法称为断言(assert)。
使用unittest测试框架时,有很多的断言方法,下面介绍几种常用的断言方法:assertEqual、assertIn、assertTrue。
一、测试代码
import unittest
class Test(unittest.TestCase):
# 判断 a == b
def test01(self):
a = 1
b = 1
self.assertEqual(a, b)
# 判断 a in b
def test02(self):
a = "hello"
b = "hello world!"
self.assertIn(a, b)
# 判断 a is True
def test03(self):
a = True
self.assertTrue(a)
# 失败用例
def test04(self):
a = "张三"
b = "李四"
self.assertEqual(a, b)
if __name__ == "__main__":
unittest.main()
二、自定义报错信息
1)分析assertEqual断言方法
assertEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '==' operator.
# 如果两个对象不相等,就返回失败,相当于return: first == second。
2)该断言方法中除了用于比较的两个参数first和second外,还有第三个参数msg=None,这个msg参数就是在断言失败后,可以自定义报错信息。
import unittest
class Demo(unittest.TestCase):
def test01(self):
a = 'zhangsan'
b = 'lisi'
self.assertEqual(a, b, "失败原因:{} != {}".format(a, b))
if __name__ == '__main__':
unittest.main()
三、常用的断言方法
# 判断两个参数是否相等:first == second
assertEqual(self, first, second, msg=None)
# 判断两个参数是否不相等:first != second
assertNotEqual(self, first, second, msg=None)
# 判断字符串member是否包含在字符串container中
assertIn(self, member, container, msg=None)
# 判断字符串member是否不包含在字符串container中
assertNotIn(self, member, container, msg=None)
# 判断是否为真:expr is True
assertTrue(self, expr, msg=None)
# 判断是否为假:expr is False
assertFalse(self, expr, msg=None)
# 判断是否为None:obj is None
assertIsNone(self, obj, msg=None)
# 判断是否不为None:obj is not None
assertIsNotNone(self, obj, msg=None)
标签:__,None,27,unittest,assert,second,msg,self
From: https://blog.csdn.net/zhangzhan0813/article/details/139479942