Unit, Integration and Mocking
Basketly's discount function works perfectly on its own. The payment service works perfectly on its own. Put together, customers are charged ₹5.40 instead of ₹540, because one side counts in rupees and the other in paise. Each piece passed its own tests; the bug lived in the join.
The rule
Unit tests one piece alone; integration tests the joins; mocks fake the neighbours.
A unit test checks the smallest useful piece of code, usually one function, on its own. Unit tests are fast (thousands run in seconds), precise (a failure points at one function) and mostly written by developers.
An integration test checks that two or more pieces work together: the app and its database, the order service and the payment gateway, the front end and the API. They are slower but catch mismatches that unit tests cannot see.
A mock is a stand-in for a real dependency. To unit test the order total without charging real cards, you give the code a fake payment gateway whose answer you control:
test("a declined payment leaves the order unpaid", () => {
const fakeGateway = { charge: () => "declined" };
const order = placeOrder({ subtotal: 600, coupon: "SAVE10" }, fakeGateway);
expect(order.total).toBe(540);
expect(order.status).toBe("unpaid");
});Mocks make tests fast and repeatable, and let you simulate rare events like a declined card. Their danger is that a mock behaves the way you imagine, not the way the real thing does.
Teams usually aim for many unit tests, fewer integration tests and a small number of full end-to-end tests: a shape often drawn as the test pyramid.
The shortcut
Ask "Where could this bug live?" Inside one function: unit test. Between two parts: integration test. And whenever a unit test needs something slow, costly or unpredictable, mock it.
Inside one function
Does
applyCoupongive ₹540 for ₹600? Unit test, no dependencies.
The trap is trusting a wall of green unit tests with mocks as proof that the system works. Mocks agree with your assumptions; only integration tests check them.
Drills
Answer fast — trust the rule.
A test checks only that applyCoupon turns a ₹600 cart with SAVE10 into ₹540. What kind is it?
Why mock the payment gateway in a unit test?
Which bug can only an integration test catch?
In the test pyramid, which tests should be most numerous?
Remember
- Unit tests one piece alone; integration tests the joins; mocks fake the neighbours.
- Ask "Where could this bug live?": inside a function, or between parts.
- Mocks agree with your assumptions; integration tests check them.
