mytest.py
import unittest
def add(a, b):
return a + b
class MyTest(unittest.TestCase):
def test_add(self):
self.assertEqual(8, add(5, 3))
if __name__ == '__main__':
unittest.main()
import unittest
person = {'name':'Nike', 'age': 20}
number = [1, 3, 2, 88, 7, 44]
s = '测试'
class TestAssert(unittest.TestCase):
def test_assert_method(self):
# self.assertEqual('Nike', person.get('name')) #判断是否相等
# self.assertTrue('测试' in s) #判断某个内容等于对象
# self.assertIn('测试', s) #判断内容在对象里
# self.assertAlmostEqual(3.3, 1.1 + 2.2) #判断是否约等于
# self.assertIs(True+1, 2) #判断是否为同引用
# self.assertIsNone(person('Name', None)) #判断是否为空
# self.assertIsInstance(s, str) #
self.assertGreater(-7, number[0]) #判断-7是否大于1
if __name__ == '__main__':
unittest.main()
示例:
calculator.py
class Calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def substract(self):
return self.x - self.y
if __name__ == '__main__':
c = Calculator(5, 3)
print(c.add())
calculator_test.py
from calculator import Calculator
class CalculatorTest(unittest.TestCase):
def setUp(self):
self.c = Calculator(5, 3)
def test_add(self):
# c = Calculator(5, 3)
self.assertEqual(8, self.c.add())
def test_subtract(self):
# c = Caculator(8, 4)
self.assertEqual(2, self.c.subtract)
def tearDown(self):
def self.c #关闭
if __name__ == '__main__':
unittest.main()