Automatic injection dependencies for unit testing

Coming from a Java background, I am working on php codebase and want to add unit tests for my code.

I have a service class that has a DAO class as shown below:

class ServiceClass {

  private $daoClass;

  public function methodToTest(){}
}

      

I am not providing a constructor, nor am I adding a setter method for the property daoClass

. This is because it will be injected using the PHP-DI IoC container.

For unit testing, I use phpunit

, so I mock an object daoClass

and use reflection to inject that property directly (since there is no constructor or setter for this property).

In java, we can easily do this without reflection using annotation @InjectMocks

or MockitoAnnotations.initMocks

.

I cannot find a similar way to do this in phpunit

.

Also, another but related question, is there any way in my test, I can create a private property and annotate it with some tag and it is automatically converted to a mock object instance? Like the way mockito in Java does this @Mock

annotation.

+3


source to share


1 answer


I don't know myself because of any mock annotation (see first comment for such a link), but for testing purposes, you could create your own mock for such service classes in plain PHP that you use in testing. It's pretty straight forward and only requires autoloading to be properly configured for development. This has the advantage that your library comes with suitable layouts, which you would otherwise mix into production code with test-only annotations but propagated into a non-competitive context.



This may not be exactly what you're looking for when doing Java, but I've made good PHP experience with such handwritten test helpers, especially when it comes to some of the class families. In the end they are very useful and can repeat tests many times. Sometimes they are even needed, as dynamically generated mocks cannot express and assert what might be required when testing.

0


source







All Articles