Python Unit Test Framework unittest Concise usage examples

Source: Internet
Author: User
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

5. Call the Unittest.main () method to run all methods that begin with test
Copy the Code code as follows:


if __name__ = = ' __main__ ':
Unittest.main ()

Examples are as follows
The class being tested

Copy the Code code as follows:


#!/usr/bin/python
#coding =utf-8

Class computer (object):
@staticmethod
def add (A, B):
return a + B;

@staticmethod
Def sub (A, b):
return a-B;

Test class

Copy the Code code as follows:


#!/usr/bin/python
#coding =utf-8
Import UnitTest
From testee import computer

Class Tester (UnitTest. TestCase):
def 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 ()

Operation Result:
Copy the Code code as follows:


----------------------------------------------------------------------
Ran 2 Tests in 0.000s
Ok
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.