Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

54
  • 14
    I disagree with your assertion that DI is about unit testing. Facilitating unit testing is just one of the benefits of DI, and arguably not the most important one. Commented May 29, 2018 at 12:44
  • 7
    I disagree with your premise that unit testing and DI are so close. By using a mock/stub, we make the test suite lie to us a bit more: the system under test gets further from the real system. That's objectively bad. Sometimes that's outweighed by an upside: mocked FS calls don't require cleanup; mocked HTTP requests are fast, deterministic and work offline; etc. In contrast, every time we use a hard-coded new inside a method we know that the same code running in production was running during tests. Commented May 29, 2018 at 19:44
  • 8
    No, it’s not “is unit testing bad?”, it’s “is mocking (a) really necessary, and (b) worth the increase in complexity incurred?” That’s a very different question. Unit testing isn’t bad (literally nobody is arguing this), and it’s definitely worth it in general. But not all unit testing requires mocking, and mocking does carry a substantial cost so it should, at least, be used judiciously. Commented May 30, 2018 at 9:17
  • 6
    @Ewan After your last comment I don’t think we agree. I’m saying that most unit tests don’t need DI [frameworks], because most unit tests don’t need mocking. In fact, I’d even use this as a heuristic for code quality: if most of your code can’t be unit tested without DI/mock objects then you’ve written bad code that was too rightly coupled. Most code should be highly decoupled, single responsibility and general-purpose, and be trivially testable in isolation. Commented May 30, 2018 at 10:54
  • 5
    @Ewan Your link gives a good definition of unit testing. By that definition my Order example is a unit test: it's testing a method (the total method of Order). You're complaining that it's calling code from 2 classes, my response is so what? We're not testing "2 classes at once", we're testing the total method. We should not care how a method does its job: those are implementation details; testing them causes fragility, tight coupling, etc. We only care about the method's behaviour (return value and side effects), not the classes/modules/CPU registers/etc. it used in the process. Commented May 31, 2018 at 14:12