开发者

What's the correct way to stub functionality for PHPUnit testing?

开发者 https://www.devze.com 2023-01-21 05:48 出处:网络
I\'m trying to write some unit tests for a class that connects t开发者_Python百科o an API. What I want to do is alter the class so that instead of actually connecting to the API, it instead loads a p

I'm trying to write some unit tests for a class that connects t开发者_Python百科o an API.

What I want to do is alter the class so that instead of actually connecting to the API, it instead loads a pre-fetched constant fixture. The method within the class that actually does the cURL request and returns the data is protected, and this is the one I want to change to instead return the contents of the fixture file.

My question is what's the best way to do this?

I've read about mock objects in PHPUnit, but because the method I want to change is internal and protected, I don't think I can use those right?

Am I correct in assuming I will need to extend the class and alter the method myself?

Thanks.


The purpose of Mocks and Stubs is to replace relying on functionality of dependencies, e.g. when you have something like

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

where $apiConnector is the dependency used to make the call to the API, then you stub or mock that dependency with your own implementation. Since that dependency is invoked through it's public facing interface by Foo, you stub the method that triggers the protected method within the dependency.

If, however, there is no dependency, but the call to the API is made from the testclass, then you have to write a custom class that extends your testclass and implements it's own API calling function, e.g.

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

You will then test this class instead of the actual class.

If your class is actually connecting to a WebService, see the chapter Stubbing and Mocking WebServices

0

精彩评论

暂无评论...
验证码 换一张
取 消