Python 使用unittest模块进行‘类’测试

本文详细介绍了如何在Python中使用unittest模块进行类级别的函数测试,特别是如何通过setUp方法创建被测试类实例,并利用各种断言方法如assertEqual,assertFalse等来验证函数功能。
摘要由CSDN通过智能技术生成

与进行函数测试类似。

不同之处在于:

在测试类中,通常定义setUp(self)函数,在其中生成一个“被测试类”的实例,并把该实例,作为测试类的成员,在该类的各个测试用例中使用。这样就不用为每个用例生成一次被测试类的实例。

举例说明,被测试代码如下,该代码被存储在文件employee_function.py中:

class Employee:
    def __init__(self,name,age,salary,ifmarried,*abilities):
        self.name = name
        self.age = age
        self.salary = salary
        self.ifmarried = ifmarried
        self.abilities = abilities
    def show_basic_info(self):
        info = f"name:{self.name} age:{self.age} salary:{self.salary}"
        return info
    def salary_increase(self,amount=5000):
        self.salary += amount
    def if_married(self):
        return self.ifmarried
    def if_has_the_ability(self,ability):
        try:
            self.abilities.index(ability)
            return True
        except:
            return False
    def show_abilities(self):
        result = ''
        for ability in self.abilities:
            result += ability
            result += '/'
        return result

测试代码如下:

import unittest # unittest is the module used to do the test
from employee_function import Employee # get_formatted_name is the function needed to be test

class EmployeeTestCase(unittest.TestCase): # class used to do test
    def setUp(self):
        self.my_employee = Employee('Emiliy','33',150000,False,'Python','MySQL','JS')
    def test_show_basic_info(self):
        info = self.my_employee.show_basic_info()
        self.assertEqual(info,'name:Emiliy age:33 salary:150000')
    def test_salary_increase(self):
        amount = 10000
        self.my_employee.salary_increase(amount)
        self.assertEqual(self.my_employee.salary,160000)
    def test_if_married(self):
        self.assertFalse(self.my_employee.if_married())
    def test_if_has_the_ability_for_true(self):
        ability = 'Python'
        self.assertTrue(self.my_employee.if_has_the_ability(ability))
    def test_if_has_the_ability_for_false(self):
        ability = 'C++'
        self.assertFalse(self.my_employee.if_has_the_ability(ability))
    def test_show_abilities(self):
        result = 'Python/MySQL/JS/C++/'
        self.assertNotEqual(self.my_employee.show_abilities(),result)

    def test_show_abilities_content(self):
        ability_list = self.my_employee.show_abilities().split('/')
        self.assertIn('Python',ability_list)

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

在测试类 EmployeeTestCase 中一共包含8个函数。

第一个函数setUp(self)中包含此次测试所有用例需要用到的被测类实例:my_employee

剩余的每个函数都是一个测试用例,对应被测类中的一个功能函数。

这里用到的‘断言’种类有:

1)assertEqual(a,b)

2)assertFalse(x)

3)assertTrue(x)

4)assertNotEqual(a,b)

5)assertIn(item,list)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值