在python中unitest存款金额

时间:2018-05-30 02:57:16

标签: python unit-testing

我是python中单元测试的新手,这是我的第一次单元测试。我不知道我是在进行正确还是错误的单元测试,需要一些帮助。我必须测试功能,在第一个功能我想测试合法存款,在第二个功能我想测试非法存款,如存款" apple"或者"蜥蜴"而不是金额。由于我是单元测试的新手,我对它有很多困惑。我读了不同的帖子,但在我的情况下,我仍然难以为这两个函数编写单元测试。

bankaccount.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()  

1 个答案:

答案 0 :(得分:2)

你可以这样做:

当提供给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()