First, the test level
1, unit testing
- Testing the basic unit of the code (function, method)
- Given certain conditions to determine whether the results in line with expectations
- A relative to the whole process, simplifies testing unit test task
- unittest module
import unittest
def add(a, b):
return a + b
def subtract(a, c):
return a - b
class MyTest(unittest.TestCase):
def test_add(self):
self.assertEqual(8, add(5, 4)) #断言是否相等
def test_subtract(self):
self.assertEqual(2, subtract(5, 3))
if __name__ == '__main__':
unittest.main()
2, integration testing
3, system testing
4, acceptance testing
5, regression testing
Second, the code organization
1, affirm
- assertEqual (value, expression) are equal
- assertTrue () is true
- assertIn () contains
- assertAlmostEqual () if approximately equal
- assertIs () whether the same references
- assertIsNone () is empty
- assertIsInstance () whether a type instance
- assertGreater () is greater than
import unittest
person = {'name':'Mike', 'age': 20}
numbers = [1, 2, 3, 88, 7, 44]
s = '优品课堂 codeclassroom.com'
class TestAssert(unittest.TestCase):
def test_assert_method(self):
#self.assertEqual('Mike', 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.get('Name', None))
#self.assertIsInstance(numbers[0], int)
#self.assertGreater(7, numbers[0])
if __name__ == '__main__':
unittest.main()
2, the apparatus
- Test case class inherits from unittest.TestCase
- test_ defined functional test function name
- setUp () function is defined in the initialization code prepared
- tearDown () function to perform cleanup work
class Calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtract(self):
return self.x - self.y
if __name__ == '__main__':
c = Calculator(5, 3)
print(c.add())
import unittest
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 =Calculator(8, 4)
self.assertEqual(4, self.c.subtract())
def tearDown(self):
del self.c
if __name__ == "__main__":
unittest.main()