Python Unit Test Framework UnitTest Concise use example _python

Source: Internet
Author: User

Test steps
1. Import UnitTest Module
Import UnitTest

2. Classes that write tests inherit unittest. TestCase
Class Tester (UnitTest. TestCase)

3. The method of writing tests must begin with test
def test_add (self)
def test_sub (self)

4. Use the method provided by TestCase class to test the function point

5. Invoke the Unittest.main () method to run all methods beginning with test

Copy Code code as follows:

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

Examples are as follows
tested Class

Copy 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;<strong> </strong>

Test class

Copy 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 ()

Run Result:

Copy Code code as follows:

----------------------------------------------------------------------
Ran 2 Tests in 0.000s
Ok

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.