oop - Is object composition without dependency injection a bad thing? -


When unit-testing objects have a creation relationship with other objects (a "is-a" relationship) As I think, if you are using any type of dependency injection, you can actually mock the object that you create. Therefore, the following types of code make unit-testing very difficult and can therefore be considered bad thing:

  & lt ;? Php class aSampleClass {Private $ Dependency; Public function __ composition () {$ this- & gt; Dependency = new another class; }}  

This toy example is easily converted to a manufacturer of a otherClass object as a parameter and is changed to use dependency injection , But this is always the case. Is there an object structure of the above form (where "new" operator is used directly in class implementation) is a bad thing? Do you always try and write a class so that it can be thoroughly tested in the isolation of its institutions?

Use of dependency injection starts to dodge me when you are using simple price objects (in the language of the domain -Deven design) such as a date, or a money object in those cases, it Just think of adding Value Object directly to the value. For example:

  & lt ;? Php class second sample class {public function getTimeDifferencePhrase () {$ now = new date_Time; $ Then = new date time (time () - 60 * 60 * 24); Return $ now-> Relative timefish ($ again); }}  

Definitely, in this example, it makes more sense for unit tests of anotherSampleClass so that date_Time Objects instead of using mock objects or test doubles

Thoughts?

It depends on Dependency injection, you are testing Solves the problem of testing the class, without worrying about the reliance on external services (which may fail, the test data is not there, or otherwise unsuitable for a unit test).

To copy the T-value object (or a string, int, etc.) just to check that your class correctly created it and called the inter operator ... all parts of the implementation And this is not really relevant to the test.

You can, however, check that your getRelativeTimeDifferencePhrase was correctly passed "24 hours ago" when 60 * 60 * 24 seconds Passed

Then you will realize that your hard coding time () leads to a delicate test - as you can not predict with enough accuracy When will your code be time () will run back This will be a RealTimeService , which will implement a seam that you can control

by starting a class with a real time service You will not leave any way to inject your the duration of the service - so that you can code the code. is it, you will then end up passing your constructor to a ITIMEService . Now, you have dependency injection I;)


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -