What if you could test your code without waiting or risking real-world consequences?
Why Stub objects in JUnit? - Purpose & Use Cases
Imagine testing a car's navigation system but you have to drive the whole route yourself every time to check if the system reacts correctly.
Or testing a payment system that requires real money transactions for every test.
Manually performing these tests is slow, tiring, and risky.
It's easy to make mistakes or miss cases because you can't repeat exactly the same conditions every time.
Also, relying on real external systems can cause delays and unpredictable failures.
Stub objects act like simple, fake versions of real parts your code talks to.
They give back fixed answers instantly, so you can test your code quickly and safely without depending on real systems.
RealPaymentService payment = new RealPaymentService(); payment.process(amount); // actually sends money
StubPaymentService payment = new StubPaymentService(); payment.process(amount); // returns fixed success response
Stub objects let you test your code in isolation, making tests fast, reliable, and easy to repeat.
When testing a shopping app, you use a stub for the payment gateway so you don't spend real money but still check if your app handles payment success or failure correctly.
Manual testing with real dependencies is slow and error-prone.
Stub objects simulate parts of the system with fixed, simple behavior.
This makes automated tests faster, safer, and more reliable.