Python's unit Test framework Pyunit is very similar to that of Java, and here's an example of unit testing of the methods in the module:
Implementation code: Enter a list of integers to determine if there are duplicate numbers, or return False if there is true
Class Solution:
# @param {integer[]} nums
# @return {Boolean}
def containsduplicate (self, nums):
Return len (nums) > Len (Set (Nums))
Unit test code is as follows, there are two methods, one is to write different test cases into different methods of test class, called separately. Such a program needs to select Run As->python unit Test at runtime. Or it is called with Unittest.main () in the main () function. Another approach is to use the Testsuite class in the main () function to assemble the test case into a test set and run it together so that it can run as a Python program type at run time, rather than as the type of unit test.
Import unittest
from Solution Import Solution
Class MyTest (unittest. TestCase):
def setUp (self):
Self.testclass = solution ()
def testCase1 (self):
self.assertequal (False, Self.testclass.containsDuplicate ([1,2,3,4,5,6]), ' Test failed! ')
def testCase2 (self):
Self.assertequal (True, Self.testclass.containsDuplicate ([1,2,3,3,5,6]), ' Test failed! ')
def testCase3 (self):
Self.assertequal (True, Self.testclass.containsDuplicate ([1,1,1,3,5,6]), ' Test failed! ')
def tearDown (self):
self.testclass = None
If __name__ = = ' __main__ ':
#方法一, call it directly, and run all test cases that begin with test
#unittest. Main ()
#方法二, assemble the specified test cases into a test set and run them together
Suite = UnitTest. TestSuite ()
Suite.addtest (MyTest (' testCase1 '))
Suite.addtest (MyTest (' TestCase2 '))
Suite.addtest (MyTest (' testCase3 '))
#也可以不用上边的分别组装的方法, this line of code can return all test case sets that have a beginning with test, similar to the effect of method one
#suite = UnitTest. Testloader (). Loadtestsfromtestcase (MyTest)
Runner = UnitTest. Texttestrunner ()
Runner.run (Suite)
Python Unit Test framework