Hacker News new | ask | show | jobs
by nbevans 4735 days ago
No the single greatest benefit that a IOC container provides is object lifetime and scoping management. The next greatest benefit is the ability to decompose your code base into a single responsibility adhering components with good decoupling and namespace cohesion characteristics.

Testing is very low down on the list of advantages of a IOC container. And even then, most people that think they're doing testing properly with a IOC container are doing it wrong. Hint: "Re-binding" your container by forcing it to drop an existing service implementation and replacing it with your mock/test implementation is "doing it wrong".

The reason there is always so much discourse around DI and IOC is because very few programmers actually bothered to learn, and grok it, even if they think they already have.

2 comments

> Testing is very low down on the list of advantages of a IOC container. And even then, most people that think they're doing testing properly with a IOC container are doing it wrong. Hint: "Re-binding" your container by forcing it to drop an existing service implementation and replacing it with your mock/test implementation is "doing it wrong".

What part of that is wrong? I may be missing your focus, but that sounds right for unit testing.

It's wrong because your unit tests, just like your application, should not be aware of the presence of an IoC container except at the absolute composition root.

Your unit test libraries should have their own composition roots of their own and it is at this level, in configuring the IoC "modules" (as they are often called) that special mock services would be provided.

If your test cases are littered with crap concerning your IoC container, re-binding stuff, then something is badly wrong. Sadly, pretty much all projects I've seen that use IoC end up writing their tests in this way. Someone wasn't thinking.

Your tests should be treated with the same adherence to SOLID principles as your application code. They are first class citizens of your code base. So why dirty your tests by having them coupled to your IoC container?

I agree. Testing with heavily mocked implementations is basically useless. Especially under time pressure, I tend to focus more on system and integration tests than on cute unit tests that tend to find issues that never occur in practice and don't find issues that occur when the first user has his first minutes with the system.

"Hooray, my setName sets the name correctly!" - well, my congratulations.