This lesson explores testing classes in Python, focusing on the BankAccount class and its methods for deposits, withdrawals, and interest collection.
In this lesson, we explore how to test classes in Python by building on our previous experience with testing simple functions. While testing functions is usually straightforward, testing classes requires writing more code and ensuring that each method behaves as expected. Here, we illustrate this process with a simple dummy class called BankAccount, which models a person’s bank account by incorporating methods for deposits, withdrawals, and interest collection, along with a helper function for division.Below is the consolidated code snippet defining the BankAccount class:
Many of the tests for basic functions (such as subtract, multiply, and divide) have already been implemented. For example, test outputs might look similar to the following:
We start by verifying that we can set an initial balance when creating a new BankAccount. For example, providing an initial balance of 50 should result in the account reflecting that balance:
Next, we test the withdraw functionality. For instance, starting with a balance of 50 and withdrawing 20 should leave the account with a balance of 30:
Similarly, it’s essential to confirm that the deposit method correctly increases the balance. Starting from a balance of 50 and depositing 30 should update the balance to 80:
The final test checks the collect_interest method. Given an initial balance, applying this method should multiply the balance by 1.1. For example, a starting balance of 50 is expected to become roughly 55. However, due to floating-point arithmetic, the result might slightly differ (e.g., 55.000000000001). To handle this, the test uses the round function:
Due to floating-point precision issues in Python, rounding the balance ensures accurate comparisons in tests.
Copy
Ask AI
def test_collect_interest(): bank_account = BankAccount(50) bank_account.collect_interest() # Round the balance to account for floating point precision issues assert round(bank_account.balance, 6) == 55
The complete suite of tests may produce output akin to:
This lesson demonstrated how to write and organize tests for a Python class. We covered testing the constructor, deposit, and withdrawal methods, as well as handling floating-point precision when applying interest calculations. For more insights into Python testing, consider exploring pytest documentation.