I ended up in a discussion with one of our my colleagues about how to setup a unit-test for testing a service class.
When setting up the test case one of us suggests mocking the actual class that we are testing, while the other prefers to make an instance of the class and only mocking the dependencies.
So let's say we are testing SomeService
One solution would be to mock the actual service and test the mock:
$firstDependency = //create mock for first dependency
$secondDependency = //create mock for second dependency
$this->someService = $this->getMockBuilder(SomeService::class)
->setMethods(null)
->setConstructorArgs(array($firstDependency, $secondDependency))
->getMock();
// continue testing $this->someService which is a mock
The other solution would be to test the instance of the service and only mocking the dependencies:
$firstDependency = //create mock for first dependency
$secondDependency = //create mock for second dependency
$this->someService= new SomeService($firstDependency, $secondDependency);
// continue testing $this->someService which is direct instance of SomeService
Which of these solutions is considered best practice?
Answers preferably with some reference to official php-unit documentation or other reliable sources.
Aucun commentaire:
Enregistrer un commentaire