简介
import unittest
class TestStringMethods(unittest.TestCase): # 需要继承TestCase类
def test_upper(self): # 所有的测试方法都需要以test开头
self.assertEqual('foo'.upper(), 'FOO') # assertEqual检测是否相等
def test_isupper(self):
self.assertTrue('FOO'.isupper()) # 检测是否为真
self.assertFalse('Foo'.isupper()) # 检测是否为假
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError): # 验证是否引发异常
s.split(2)
if __name__ == '__main__':
unittest.main()
工作环境fixture
setUp(),tearDown()
断言方法
方法 | 检查 | 说明 |
---|---|---|
assertEqual(a, b) | a == b | #如果相比较的是list,dict等类型会调用特定的函数 |
assertNotEqual(a, b) | a != b | |
assertTrue(x) | bool(x) 是 True | |
assertFalse(x) | bool(x) 是 False | |
assertIs(a, b) | a 是 b | 是否是同一个对象 |
assertIsNot(a, b) | a 是 不是 b | |
assertIsNone(x) | x 是 无 | |
assertIsNotNone(x) | x 是 不是 无 | |
assertIn(a, b) | a 在 b | |
assertNotIn(a, b) | a 不是 在 b | |
assertIsInstance(a, b) | isinstance(a, b) | |
assertNotIsInstance(a, b) | 不是 isinstance(a, b) |