unittest框架的TestCase提供了如下断言方法
方法 | 检查 | 版本 |
assertEqual(a,b) | a==b | |
assertNotEqual(a,b) | a!=b | |
assertTrue(x) | bool(x) is True | |
assertFale(x) | bool(x) is False | |
assertIs(a,b) | a is b | 3.1 |
assertNot(a,b) | a is not b | 3.1 |
assertNone(x) | x is None | 3.1 |
assertNotNoe(x) | x is not None | 3.1 |
assertIn(a,b) | a is in b | 3.1 |
assertNotIn(a,b) | a is not in b | 3.1 |
assertIsInstance(a,b) | isinstance(a,b) | 3.2 |
assertNotIsInstance(a,b) | not isinstance(a,b) | 3.2 |
assertEqual(a,b,msg=None)断言第一个参数和第二个参数是否相等,不相等测试失败,msg可选参数,用于定义测试失败时打印的信息
文件isPrime
import unittest #判断是否为质数 class IsPrime(): def __init__(self,number): self.number=number def isPrime(self): if self.number<=1: return False for i in range(2,self.number): if self.number % i ==0: return False return True class TestIsPrime(unittest.TestCase): def setup(self): print('test start') def test_case(self): j=IsPrime(5) print(j.isPrime()) self.assertTrue(j.isPrime(),msg='not is prime') def teardown(self): print('test end') if __name__ =='__main__': unittest.main()