* We define a `Calculator` class with methods for basic arithmetic operations.
* We create a `TestCalculator` class that inherits from `unittest.TestCase`.
* In the `setUp` method, we create an instance of the `Calculator` class that will be used for testing.
* We define test methods for each operation:
* `test_add`: Tests the `add` method with different inputs.
* `test_subtract`: Tests the `subtract` method with different inputs.
* `test_multiply`: Tests the `multiply` method with different inputs.
* `test_divide`: Tests the `divide` method with different inputs, including a test for division by zero.
To run the tests, save both files and execute the following command:
bash
python m unittest test_calculator.py
If all tests pass, you should see an output indicating the number of tests run and that they all passed.
Additional Example with More Advanced Testing
Let's assume we have a more complex class, like a simple bank account system:
bank_account.py
python
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
if amount < 0:
raise ValueError(Deposit amount cannot be negative)
self.balance += amount
def withdraw(self, amount):
if amount < 0:
raise ValueError(Withdrawal amount cannot be negative)
if amount self.balance:
raise ValueError(Insufficient funds)
self.balance = amount
def get_balance(self):
return self.balance
test_bank_account.py
python
import unittest
from bank_account import BankAccount
class TestBankAccount(unittest.TestCase):
def test_default_initial_balance(self):
account = BankAccount()
self.assertEqual(account.get_balance(), 0)
def test_insufficient_funds(self):
account = BankAccount(50)
with self.assertRaises(ValueError):
account.withdraw(100)
def test_negative_deposit(self):
account = BankAccount(50)
with self.assertRaises(ValueError):
account.deposit(20)
def test_negative_withdrawal(self):
account = BankAccount(50)
with self.assertRaises(ValueError):
account.withdraw(20)
if __name__ == '__main__':
unittest.main()
In this example, we test various scenarios for a bank account, including:
* Initial balance
* Depositing money
* Withdrawing money
* Attempting to withdraw more than the balance
* Attempting to deposit or withdraw a negative amount
Running these tests helps ensure that our `BankAccount` class behaves as expected under different conditions.