Fix the Broken Mock
Advanced · Fix the bug · from Python Mocking and Fixtures: Test Code with External Dependencies
From the lesson: Python Mocking and Fixtures: Test Code with External Dependencies
Before car companies test a new vehicle in a real crash, they use a crash test dummy. The dummy is a stand-in for a real person - it behaves similarly enough to be useful, but nobody gets hurt.
Read the lessonThis test is supposed to verify that calculate_total applies a 10% discount. But the mock is set up incorrectly - it's not returning the data the function expects. Fix the MockPricingService so the test passes and prints Discount test passed!.
class MockPricingService:
def get_price(self, item):
# Bug: returns the wrong data format!
return item
def calculate_total(pricing, items):
total = 0
for item in items:
total += pricing.get_price(item)
discount = total * 0.10
return total - discount
def test_discount():
mock = MockPricingService()
items = ['shirt', 'pants', 'hat']
result = calculate_total(mock, items)
# Prices should be: 25.0 + 40.0 + 15.0 = 80.0
# After 10% discount: 80.0 - 8.0 = 72.0
assert result == 72.0
test_discount()
print('Discount test passed!')
More Mocking exercises
- Create a Mock Email ServiceIntermediate
- Predict the Mock BehaviorIntermediate
- Mock the ClockAdvanced
- Build a Test FixtureAdvanced