Python_测试

文章讲述了如何在Python中编写一个Employee类,包括初始化方法init和增加年薪的方法give_raise。同时介绍了如何使用pytest进行单元测试,包括使用fixture创建测试用例和编写test_give_default_raise和test_give_custom_raise测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

‘’'测试函数
断言 assert+布尔表达式 一般写在函数或者类中
若文件和测试文件位于同一个文件夹下测试引入方法: from 文件名 import 函数名

‘’’
mytest.py:

def addtr(a,b):
    return a+b

test_测试.py

from mytest import addtr
def test_add1():# 注意测试函数要以test开头
    assert addtr(3,8)==11

def test_add2():
    assert addtr(-4, 8) == 2

‘’‘练习11-3:雇员
编写一个名为 Employee 的类,其方法 init()接受名、姓和年薪,并将它们存储在属性中。
编写一个名为 give_raise()的方法,它默认将年薪增加5000美元,但也能够接受其他的年薪增加量。
为Employee 编写一个测试用例,其中包含两个测试方法:
test_give_default_raise()和test_give_custom_raise()。在不使用夹具的情况下编写这两个测试,并确保它们都通过了。
然后,编写一个夹具,以免在每个测试函数中都创建一个Employee对象。重新运行测试,确认两个测试都通过了。
‘’’
class_init.py

class Employee:
    def __init__(self,lname,fname,money):
        self.lname=lname
        self.fname=fname
        self.money=money
    def give_raise(self,add=5000):
        self.money+=add
****test_class_init.py****
```import pytest
from class_init import Employee
@pytest.fixture
def employee1():#fixture所装饰的会在每个测试用例执行之前执行一遍
    employee1=Employee('王','婵',10000)
    return employee1
def test_give_default_raise(employee1):
    employee1.give_raise()
    assert employee1.money==15000
def test_give_custom_raise(employee1):
    employee1.give_raise(10000)
    assert  employee1.money==20000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个学术垃圾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值