在python中进行Unitest以存放amoun

2024-05-23 17:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python单元测试的新手,这是我的第一个单元测试。我不知道我做的单元测试是对的还是错的,需要一些帮助。我必须测试功能,在第一个功能中我要测试合法存款,在第二个功能中我要测试非法存款,比如用“苹果”或“蜥蜴”代替金额存款。由于我是单元测试的新手,我对它有很多困惑。我读了不同的文章,但在我的情况下,我仍然觉得很难为这两个函数编写单元测试。你知道吗

你知道吗银行账户.py你知道吗

class BankAccount():

    def __init__(self):

        self.account_number=0
        self.pin_number=""
        self.balance=0.0
        self.interest=0.0
        self.transaction_list=[]

    def deposit_funds(self, amount):
        self.balance+=amount


    def withdraw_funds(self, amount):

        if amount<=balance:
            self.balance-=amount

import unittest

from bankaccount import BankAccount

class TestBankAcount(unittest.TestCase):

    def setUp(self):
        # Create a test BankAccount object
        self.account = BankAccount()

        # Provide it with some property values        
        self.account.balance        = 1000.0

    def test_legal_deposit_works(self):
        # code here to test that depsositing money using the account's
        # 'deposit_funds' function adds the amount to the balance.

     self.assertTrue(100,self.account.deposit_funds(100))


 def test_illegal_deposit_raises_exception(self):
            # code here to test that depositing an illegal value (like 'bananas'
            # or such - something which is NOT a float) results in an exception being
            # raised.

unittest.main()  

Tags: thetotestself功能defaccount单元测试
1条回答
网友
1楼 · 发布于 2024-05-23 17:22:12

你可以这样做:

当提供给deposit_funds的值类型与用例不匹配时,让类引发错误。你知道吗

class BankAccount:

    def __init__(self):

        self.account_number = 0
        self.pin_number = ""
        self.balance = 0.0
        self.interest = 0.0
        self.transaction_list = []

    def deposit_funds(self, amount):
        try:
            self.balance += amount
        except TypeError:
            raise TypeError

    def withdraw_funds(self, amount):
        if amount <= balance:
            self.balance -= amount

让您的测试检测到发生这种情况时抛出TypeError。你知道吗

class TestBankAcount(unittest.TestCase):

    def setUp(self):
        self.test_account = BankAccount()
        self.test_account.balance = 1000.0

    def test_legal_deposit(self):
        expected_balance = 1100.0
        self.test_account.deposit_funds(100.0)
        self.assertEqual(expected_balance, self.test_account.balance)

    def test_illegal_deposit_raises_exception(self):
        # code here to test that depositing an illegal value (like 'bananas'
        # or such - something which is NOT a float) results in an exception being
        # raised.
        with self.assertRaises(TypeError):
            self.test_account.deposit_funds('dummy value')


if __name__ == '__main__':

    unittest.main()

相关问题 更多 >