Factory pattern and testability
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
A factory improves testability when a method genuinely needs to create one of several products at runtime and the factory is injected through a contract. The production factory can build a real client, while the test factory returns a controlled fake, so the service behavior is isolated. Simply renaming a static creation method as a factory does not create that seam, because the class still owns a hard dependency. If the service always uses one repository or client, I inject that object directly; adding a factory would only add indirection. The value comes from external, substitutable ownership of a real creation decision.
Factory pattern and testability
Direct Answer
A factory can improve testability when the code under test must create a product during an operation: inject a factory interface and have the test return a controlled fake product. A static or internally constructed factory does not provide that seam by itself. If the dependency can simply be injected as an object, direct dependency injection is usually simpler than adding a factory.
Common Mistakes & Pitfalls
- Static factory methods. They can't be overridden or injected — use instance methods or a factory interface.
- Missing the injection point. If you
new RealFactory()inside the service, you're back to a hard dependency. Inject the factory. - Business logic in the factory. Keep factories to creation/wiring, or they become hard to test themselves.
- Fake objects instead of real mocks. Use a mocking framework (Mockito) when you need to verify interactions.
Check your understanding
Answer these without looking back at the article.
- How does Mockito's @Mock differ from using a test Factory object?
- When would you use a Factory over direct Spring @MockBean injection in tests?
- Why are static factory methods bad for testability?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.