Coming from Java background, I am working on php codebase and want to add unit tests for my code.
I have a service class which has a DAO class as below :
class ServiceClass {
private $daoClass;
public function methodToTest(){}
}
I don't provide a constructor nor do I add a setter method for the daoClass
property. This is because it will get injected using PHP-DI IoC container.
For unit testing, I am using phpunit
, so I am mocking the daoClass
object and using reflection to inject that property directly (as there is no constructor or setter for that property).
In java, we can easily do this without the reflection stuff using @InjectMocks
annotation or MockitoAnnotations.initMocks
method.
I am not able to find a similar way to do this in phpunit
.
Also, a different but related question, is there any way in my test I can create a private property and annotate it with some tag, and it automatically gets converted to a mock object instance? Like how mockito in Java does it @Mock
annotation.
I don't know myself of any mock-by-annotation (see the first comment for a link of such), but for your testing purposes you could create your own mock for such service classes in plain PHP that you use in testing. This is rather straight forward and only requires that autoloading is properly configured for development. This has the benefit that your library ships with suitable mocks which otherwise you would intermix into production code with annotations that are designed for tests only but spread into non-test context.
This might not be exactly what you're looking for when coming from Java, but I have made good experiences in PHP with such "hand-written" test-helpers especially when it comes to some family of classes. In the end they are pretty useful and can safe a lot of repetition in tests. Sometimes they are even necessary as dynamically created mocks can't express and assert what might be required in testing.