Testing the args constructor in phpunit

We use Varien_Http_Client to create HTTP requests from the Magento extension, for example:

 public function callApi(…) { <SNIP> // Set default factory adapter to socket in case curl isn't installed. $client = new Varien_Http_Client($apiUri, array( 'adapter' => 'Zend_Http_Client_Adapter_Socket', 'timeout' => $timeout, )); $client->setRawData($xmlDoc->saveXML())->setEncType('text/xml'); $response = $client->request($method); $results = ''; if ($response->isSuccessful()) { $results = $response->getBody(); } return $results; } 

I understand that I should avoid checking the internal components of Varien_Http_Client ; rather, I have to verify that we send him the correct inputs and correctly process his outputs. I can make fun of Varien_Http_Client quite easily, but even if I reorganize this code so that I replace Varien_Http_Client with my layout, I don’t understand how to verify that the constructor was called with the expected arguments, since the constructor is called PHPUnit::getMock .

I do not need the layout of the object; I need a dummy class. How can I verify that the constructor was called with the expected arguments?

* (In this case, I know ways to get around this Varien_Http_Client specific Varien_Http_Client , but what can I do with more opaque third-party code?)

+4
source share
1 answer

This is what we call "erratic" code. When you create dependencies within your methods, there is no way to mock them. Each use of the β€œnew” keyword in your model is a signal that you should consider when inserting an object, rather than creating it inside. In my opinion, the only exception to this rule is the creation of a "data container" object or class factory. But in these cases, you can probably test the object because the methods will return it.

So, as you said, the method you showed needs a small refactor, for example:

 class ApiClass { protected $client; public function __construct(Varien_Http_Client $client) { $this->client = $client; } public function callApi() { $this->client->setRawData($xmlDoc->saveXML())->setEncType('text/xml'); (...) 

Best!

+3
source

Source: https://habr.com/ru/post/1488980/


All Articles