研读大牛的实例对单元测试框架unittest testcase 的深刻认识

step1:

在mathfunc.py下定义一个方法:

def add(a, b):

    return a+b

def minus(a, b):

    return a-b

def multi(a, b):

    return a*b

def divide(a, b):

    return a/b

step2:给上面方法编写测试如下:

# -*- coding: utf-8 -*-

import unittest

from mathfunc import *

class TestMathFunc(unittest.TestCase):

    """Test mathfuc.py"""

    def test_add(self):

        """Test method add(a, b)"""

        self.assertEqual(3, add(1, 2))

        self.assertNotEqual(3, add(2, 2))

    def test_minus(self):

        """Test method minus(a, b)"""

        self.assertEqual(1, minus(3, 2))

    def test_multi(self):

        """Test method multi(a, b)"""

        self.assertEqual(6, multi(2, 3))

    def test_divide(self):

        """Test method divide(a, b)"""

        self.assertEqual(2, divide(6, 3))

        self.assertEqual(2.5, divide(5, 2))

if __name__ == '__main__':

    unittest.main()

step3:执行结果

.F..

======================================================================

FAIL: test_divide (__main__.TestMathFunc)

Test method divide(a, b)

----------------------------------------------------------------------

Traceback (most recent call last):

File "D:/py/test_mathfunc.py", line 26, in test_divide

    self.assertEqual(2.5, divide(5, 2))

AssertionError: 2.5 != 2

----------------------------------------------------------------------

Ran 4 tests in 0.000s

FAILED (failures=1)

执行结果显示:一共运行了4个测试,失败了1个,并且给出了失败原因,2.5 != 2 也就是说我们的divide方法导致failing

Notes:

当在unittest.main()中加 verbosity 参数时可以控制输出错误报告的详细程度,

默认是 1,如果设为 0,则不输出每一用例的执行结果,即没有上面的结果中的

第1行;如果设为 2,则输出详细的执行结果,如下:

test_add (__main__.TestMathFunc)

Test method add(a, b) ... ok

test_divide (__main__.TestMathFunc)

Test method divide(a, b) ... FAIL

test_minus (__main__.TestMathFunc)

Test method minus(a, b) ... ok

test_multi (__main__.TestMathFunc)

Test method multi(a, b) ... ok

----------------------------------------------------------------------

FAIL: test_divide (__main__.TestMathFunc)

Test method divide(a, b)

----------------------------------------------------------------------

Traceback (most recent call last):

File "D:/py/test_mathfunc.py", line 26, in test_divide

    self.assertEqual(2.5, divide(5, 2))

        AssertionError: 2.5 != 2

----------------------------------------------------------------------

Ran 4 tests in 0.002s

FAILED (failures=1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值