PYTHON单元测试模块unittest

一些基本概念

test fixture
    A test fixture represents the preparation needed to perform one or moretests, and any associate cleanup actions. This may involve, for example,creating temporary or proxy databases, directories, or starting a serverprocess.
test case
    A test case is the smallest unit of testing. It checks for a specificresponse to a particular set of inputs. unittest provides a base class,TestCase, which may be used to create new test cases.
test suite
    A test suite is a collection of test cases, test suites, or both. It isused to aggregate tests that should be executed together.
test runner

    A test runner is a component which orchestrates the execution of testsand provides the outcome to the user. The runner may use a graphical interface,a textual interface, or return a special value to indicate the results ofexecuting the tests.

下面是简单的一个例子

#Rectangle.py

class Rectangle:
    def __init__(self,length,width):
        self.length = length
        self.width = width
        
    def girth(self):
        return 2*(self.length+self.width)
    
    def area(self):
        return self.length*self.width

#pytest.py

from Rectangle import Rectangle
import unittest

class RectangleTestCase(unittest.TestCase):
    def setUp(self):
        self.rectangle = Rectangle(10,5)  
   
    def tearDown(self):
        self.rectangle = None
   
    def testGirth(self):
        self.assertEqual(self.rectangle.girth(), 30)
   
    def testArea(self):
        self.assertEqual(self.rectangle.area(), 100)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(RectangleTestCase("testGirth"))
    suite.addTest(RectangleTestCase("testArea"))
    return suite

if __name__ == "__main__":   
    unittest.TextTestRunner().run(suite())   

运行结果如下

joe@joe:/mnt/share$ python pytest.py
.F
======================================================================
FAIL: testArea (__main__.RectangleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "pytest.py", line 15, in testArea
    self.assertEqual(self.rectangle.area(), 100)
AssertionError: 50 != 100

----------------------------------------------------------------------
Ran 2 tests in 0.007s

FAILED (failures=1)

可以看到提示有一个失败,因为在算面积的时候不正确,应该是50才对,把pytest.py的内容改一下

def testArea(self):
        self.assertEqual(self.rectangle.area(), 50)
再跑一遍试试

joe@joe:/mnt/share$ python pytest.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

这下就OK了,没有错误。


下面是一些相关资料:

PYTHON官方文档

Python Unit Testing Framework



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值