In Python, The unittest module uses UT (unit test) instances and pythonunittest
Class to be tested (Widget. py)
# Widget.py # Python 2.7.6 class Widget: def __init__(self, size = (40,40)): self.size = size def getSize(self): return self.size def reSize(self,width,height): if width <0 or height < 0: raise ValueError, 'illegal size' else: self.size = (width,height) return self.size def dispose(self): pass
Test class (Auto. py)
# Coding = utf8 # Auto. dy # Python 2.7.6 from Widget import Widget # import test class module Widget import unittest # import unittest module class WidgetTestCase (unittest. testCase): # Let all the classes that execute the test inherit from the TestCase class. You can regard TestCase as a set of methods for testing a specific class # In setUp () method. Def setUp (self): self. widget = Widget () # And the cleanup after the test is executed in the tearDown () method. setUp () and tearDown () are both defined in the TestCase class. Def tearDown (self): self. widget = None # Test the getSize method def testgetSize (self): print "Test GetSize" # Compare the returned values of the getSize () method and the expected values in the Widget class, make sure that the two are equal. # assertEqual () is also the method defined in the TestCase class. Self. assertEqual (self. widget. getSize (), (40, 40) # Test the reSize method def testreSize (self) in the Widget class: print "Test Resize" # reSize () in the Widget class () the Return Value of the method is compared with the expected value to ensure that the two values are equal. # AssertEqual () is also defined in the TestCase class. Self. assertEqual (self. widget. reSize (50,100), (50,100) # provides a global method named suite (). PyUnit calls suit () during the test execution () to determine how many test cases need to be executed. # You can regard TestSuite as a container that contains all test cases. Def suite (): suite = unittest. testSuite () suite. addTest (WidgetTestCase ("testgetSize") # Add the testgetSize () suite method to be tested. addTest (WidgetTestCase ("testreSize") # Add the method testreSize () return suite if _ name _ = "_ main _": unittest. main (defaultTest = 'suite ') # Call the global method in the main function.
Test results:
D:\Python>python27 Auto.py Test GetSize .Test Resize . ------------------------------ Ran 2 tests in 0.004s OK
Summary:
1. Step 1: Write the test class first
2. Step 2: import the unittest module and test class, and use the setup () method to prepare for the test. For example, you can use the teardown () method to clear the database after the test, for example, cancel the connection to the database and test the methods in the class one by one.
3. Step 3: Write the global method of suite () and add the methods to be tested one by one.
The test results are as follows.