Mar-10-2022, 07:37 AM
Tests are a better way than printing to check your code works. Why better? Because they'll fail if you break something - that way, you're relying on the computer to help you than a human checking the output.
Here are some example test cases:
Here are some example test cases:
import unittest from bank_account import BankAccount class TestBankAccount(unittest.TestCase): def test_a_deposit_increases_the_balance(self): account = BankAccount("Jane", "Smith") account.deposit(40) self.assertEqual(account.balance, 40) def test_withdrawing_an_amount_greater_than_the_balance_fails(self): account = BankAccount("John", "Smith", starting_balance=0) withdrawl_amount = 15 self.assertRaises(ValueError, account.withdraw, withdrawl_amount) if __name__ == "__main__": unittest.main()Given the
BankAccount
in Yoriz's post, if I take out the check in withdraw
for the amount being greater than the balance, running these gives:Output:> python3 test_bank_account.py
.F
======================================================================
FAIL: test_withdrawing_an_amount_greater_than_the_balance_fails (__main__.TestBankAccount)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_bank_account.py", line 17, in test_withdrawing_an_amount_greater_than_the_balance_fails
self.assertRaises(ValueError, account.withdraw, withdrawl_amount)
AssertionError: ValueError not raised by withdraw
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
See the docs for the unittest
module here.