使用你熟悉的编程语言(如Java、Python等),编写一个类(或函数),用于处理收支记录的录入和余额计算。 编写单元测试,确保你的代码能够正确处理各种边界情况和异常情况(如输入非法值)。
时间: 2024-09-18 13:05:07 浏览: 31
基于Java和Python语言使用函数输出一个整数的逆序数.zip
在Python中,我们可以创建一个名为`BankAccount`的类来管理收支记录和余额。首先,我们定义基本的属性和方法:
```python
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit amount must be greater than zero.")
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount <= 0 or amount > self.balance:
raise ValueError("Withdrawal amount is invalid.")
self.balance -= amount
return self.balance
def get_balance(self):
return self.balance
```
接下来,我们将编写单元测试来验证这个类的功能,包括正常操作和边缘情况:
```python
import unittest
class TestBankAccount(unittest.TestCase):
def setUp(self):
self.account = BankAccount(100)
def test_deposit_positive_amount(self):
self.account.deposit(50)
self.assertEqual(self.account.get_balance(), 150)
def test_withdraw_valid_amount(self):
self.account.withdraw(75)
self.assertEqual(self.account.get_balance(), 25)
def test_withdraw_invalid_amount(self):
with self.assertRaises(ValueError):
self.account.withdraw(-50)
def test_initial_balance(self):
account = BankAccount()
self.assertEqual(account.get_balance(), 0)
def test_deposit_zero_amount(self):
with self.assertRaises(ValueError):
self.account.deposit(0)
if __name__ == "__main__":
unittest.main()
```
阅读全文