Test steps
1. Import the UnitTest module
Import UnitTest
2. Write the test class inheritance unittest. TestCase
Class Tester (UnitTest. TestCase)
3. Methods for writing tests must begin with test
def test_add (self)
def test_sub (self)
4. Test The function points using the method provided by the TestCase class
a is b a in b
method |
checks that |
new in |
assertequal (A, b) |
a == b |
  |
assertnotequal (A, b) |
a != b |
  |
asserttrue (x) |
bool (x) is < Span class= "Pre" >true |
&NBSP; |
assertfalse (x) |
bool (x) is < Span class= "Pre" >false |
&NBSP; |
assertis (A, b) | TD style= "PADDING:2PX 5px; border-width:1px 1px 1px 0px; Border-style:solid; Border-color:rgb (221,221,221); Background-color:rgb (238,238,255) ">
2.7 |
assertisnot (A, b) |
a is not b |
2.7 |
assertisnone (x) |
x is none |
2.7 |
assertisnotnone (x) |
x is not none |
2.7 |
assertin (A, b) | TD style= "PADDING:2PX 5px; border-width:1px 1px 1px 0px; Border-style:solid; Border-color:rgb (221,221,221); Background-color:rgb (238,238,255) ">
2.7 |
assertnotin (A, b) |
a not in b |
2.7 |
assertisinstance (A, b) |
isinstance (A, b) |
2.7 |
assertnotisinstance (A, b) |
not isinstance (A, b) |
2.7 |
5. Call the Unittest.main () method to run all methods that begin with test
if __name__ = = ' __main__ ':
Unittest.main ()
Examples are as follows
The class being tested
#!/usr/bin/python#coding=utf-8class computer (object): @staticmethoddef Add (A, B): return a + B; @staticmethoddef Sub (A, b ): Return a-b;<strong></strong>
Test class
#!/usr/bin/python#coding=utf-8import unittestfrom testee Import computerclass Tester (unittest. TestCase):d EF test_add (self): Self.assertequal (Computer.add (2, 3), 5, "Test add Function") def-test_sub (self): Self.assertequal (Computer.sub (5, 1), 4, "Test sub function") if __name__ = = ' __main__ ': Unittest.main ()
? Run Result:
----------------------------------------------------------------------
Ran 2 Tests in 0.000s
Ok
Introduction to the Python Unit Test framework unittest testing process