Daan Timmer
Daan Timmer

Reputation: 15057

SOLID and unit testing. Using language provided methods/classes

So I've read about this thing called SOLID (mixed with) Writing Testable Code. And then specifically about the D part. How does one follow these guidelines when using primitive types or Methods/Classes provided by the language library.

Does one also need to use Dependency Injection for arrays (java (new int[64]) or class members of say, a FileWriter?. Do these need to be injected using DI or can the class still instantiate them?

How far should you go to following the above guidelines?

I am not looking for a language-specific answer (if possible). IMHO the answer should apply to, for ex, PHP, Python Java, heck, even C

Upvotes: 4

Views: 2307

Answers (2)

Morten
Morten

Reputation: 3854

Injecting arrays is overkill. Injecting a file writer is an absolute must. In fact injecting the writer is not enough. File writers interacts heavily with the outside world, and you do not want that. A file writer should be wrapped in its own class, and never be called directly.

Instead, inject an interface of the FileWriterWrapper. Thus the depency is controlled. Further, file interaction in unit test is a major pain. Avoid it at any cost. The same goes for database interaction. In fact all interaction with the outside world should be stubbed/mocked in unit tests.

The beauty is, that SOLID design and testability goes hand in hand. Good design means testable code. If you find it hard to test a some code, it usually indicates that there is a flaw in your design.

Upvotes: 1

k.m
k.m

Reputation: 31464

You usually don't inject primitives or DTO/POJO-like objects. Reason is that those are:

  1. Simple value holders without much business/domain logic associated
  2. Easily stubbed without any extra tools (creating array of fake data for test is not problematic)

FileWriter is different as it's in exact opposition to points above. I can't simply stub it in test and make it work without few strong assumptions - like, I assume every future developer running this code will have certain file on his machine. This usually is no-go for unit tests and one of the reasons why DI is applied in those cases.

Those problems come from fact that FileWriter serves as communication point between two unrelated components - your application and file system. Any class doing this kind of integration (between your app and DB/network/file/REST etc.) in most cases should be abstracted and injected.

Upvotes: 4

Related Questions