The before code shows a service method without any tests, risking undetected bugs. The after code adds a unit test that automatically checks for invalid input, catching errors early and enabling safe refactoring.
### Before: No automated tests
class PaymentService:
def process_payment(self, amount):
# complex logic
pass
### After: Automated unit test added
import unittest
class PaymentService:
def process_payment(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
# complex logic
return True
class TestPaymentService(unittest.TestCase):
def test_process_payment_negative_amount(self):
service = PaymentService()
with self.assertRaises(ValueError):
service.process_payment(-10)
if __name__ == '__main__':
unittest.main()