What is the correct locking method for testing PHPUnit?

I am trying to write some unit tests for a class that connects to an API.

What I want to do is change the class so that instead of actually connecting to the API, it instead loads a predefined constant. The method inside the class that actually executes the cURL request and returns the data is protected, and this is the one I want to change to return the contents of the binding file instead.

My question is the best way to do this?

I read about mock objects in PHPUnit, but since the method I want to change is internal and secure, I don’t think I can use them correctly?

Do I correctly assume that I will need to extend the class and change the method myself?

Thanks.

+4
source share
1 answer

The goal of Mocks and Stub is to replace based on dependency functionality, for example. when you have something like

class Foo { public function __construct($apiConnector) { $this->apiConnector = $apiConnector } } 

where $apiConnector is the dependency used to invoke the API, then you mute or mock this dependency with your own implementation. Since this dependency is called through it via the Foo interface, it blocks a method that runs the protected method in the dependency.

If, however, there is no dependency, but the API call is made from testclass, then you need to write your own class that extends your test class and implements its own API call function, for example.

 class FooMock extends Foo { protected function queryAPI() { return $fixture; } } 

Then you check this class instead of the actual class.

If your class actually connects to WebService, see the Stubbing and Mocking WebServices chapter.

+1
source

All Articles