CodePark/ questions / Dependency injection & inversion
START PRACTICINGPRACTICE
Backend question · Software design & patterns › Dependency injection & inversion

Why is this class hard to unit test?

class RefundService {
  private stripe = new Stripe(process.env.STRIPE_KEY!);
  private repo = new PgRefundRepository();
  async refund(orderId: string) { /* ... */ }
}
It creates its own dependencies, so a test can't substitute fakes without mocking modules or hitting real services

The class creates Stripe and the repository itself, so a test cannot give it fakes. The test must either call the real services or use module-level mocking. Mocking at module level means replacing a whole imported module for the test. The fix is to pass the dependencies in through the constructor.

"It reads an environment variable, which is never allowed in a service class" is wrong. Reading config directly is a small issue, not the root cause, and it is not forbidden.