1. Importing Test objects
2. Import the Unit Test framework: UnitTest
3. Create the inherit from UnitTest. The test class for the TestCase class, which must contain three methods: Initialize, test, end
The method name that is initialized and ended must be contained in the setup, Teardown,testcase class.
Test method, detail test step, can use asserequal to compare actual results and expected results, while in which you can define failure, prompt content, such as asserequal (c1,5, ' inconsistent with expected results ')
1 #Coding=utf-82 fromCountImportCount3 #Unit Test Framework UnitTest4 ImportUnitTest5 classTestadd (unittest. TestCase):#inheriting the TestCase class in UnitTest6 #1> test Preparation, initializing7 defsetUp (self):8 Print "Test Start"9 #2> Formal TestingTen defTestadd (self): OneC1=count (2,3) A #Assertion Function -Self.assertequal (C1.add (), 5) - #You can add an error description after the parameter, asserequal (c1,6, ' results are inconsistent with expectations ') the #3> end of work - defTearDown (self): - Print "Test End"
Assertion Syntax Explanation
Assertequal (A, b) Judge A==b
Assertnotequal (A, B) judge A! =b
asserttrue (x) bool (x) is True
assertfalse (x) bool (x) is False
Assertis (A, b) A is B
Assertisnot (A, B) A is not B
Assertisnone (x) x is None
Assertisnotnone (x) x is not None
Assertin (A, b) a in B
Assertnotin (A, b) a not in B
Assertisinstance (A, B) isinstance (A, b)
Assertnotisinstance (A, B) not isinstance (A, B)
In real-world tests, there are often several test case, usually performed using a test set.
The definition of the test class is roughly the same as above,
Then you need to define the test set and inherit from UnitTest. Testsutie,
Then add the test case defined in the test class to the test set
The execution of the test set requires a virtual performer, defined as runner=unittest. Texttestrunner ()
Finally, let the performer execute the test set. Good: Runner.run (Suite)
1 #Coding=utf-82 ImportSYS3Sys.path.append ('. \\practice')4 fromCountImportCount5 ImportUnitTest6 classTestcount (unittest. TestCase):7 defsetUp (self):8 Print 'Test Start'9 defTestadd (self):TenC1 = Count (2,3). Add () OneSelf.assertequal (c1,5) A deftestsub (self): -C2 = Count (3,3). Sub () -Self.assertequal (c2,1) the defTearDown (self): - Print 'Test Complete' -Suite =UnitTest. TestSuite () -Suite.addtest (Testcount ('Testadd')) +Suite.addtest (Testcount ('TestSub')) -Runner =UnitTest. Texttestrunner () +Runner.run (Suite)
Python Test Framework Basics