Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
HttpClientFactoryTest.php
Go to the documentation of this file.
1 <?php
7 
12 use Magento\Framework\HTTP\ZendClientFactory;
14 use \PHPUnit_Framework_MockObject_MockObject as MockObject;
15 
16 class HttpClientFactoryTest extends \PHPUnit\Framework\TestCase
17 {
21  private static $dummy = 'dummy';
22 
26  private $objectManager;
27 
31  private $config;
32 
36  private $clientFactory;
37 
41  private $client;
42 
46  private $dataEncoder;
47 
51  private $httpClient;
52 
53  public function setUp()
54  {
55  $this->objectManager = new ObjectManager($this);
56 
57  $this->config = $this->getMockBuilder(Config::class)
58  ->disableOriginalConstructor()
59  ->getMock();
60 
61  $this->client = $this->getMockBuilder(ZendClient::class)
62  ->disableOriginalConstructor()
63  ->setMethods(['setHeaders', 'setMethod', 'setUri', 'setRawData'])
64  ->getMock();
65 
66  $this->clientFactory = $this->getMockBuilder(ZendClientFactory::class)
67  ->disableOriginalConstructor()
68  ->setMethods(['create'])
69  ->getMock();
70 
71  $this->clientFactory->expects($this->once())
72  ->method('create')
73  ->willReturn($this->client);
74 
75  $this->dataEncoder = $this->getMockBuilder(EncoderInterface::class)
76  ->disableOriginalConstructor()
77  ->getMock();
78 
79  $this->httpClient = $this->objectManager->getObject(HttpClientFactory::class, [
80  'config' => $this->config,
81  'clientFactory' => $this->clientFactory,
82  'dataEncoder' => $this->dataEncoder
83  ]);
84  }
85 
86  public function testCreateHttpClient()
87  {
88  $this->config->expects($this->once())
89  ->method('getApiKey')
90  ->willReturn('testKey');
91 
92  $this->config->expects($this->once())
93  ->method('getApiUrl')
94  ->willReturn('testUrl');
95 
96  $client = $this->httpClient->create('url', 'method');
97 
98  $this->assertInstanceOf(ZendClient::class, $client);
99  }
100 
101  public function testCreateWithParams()
102  {
103  $param = ['id' => 1];
104  $storeId = 1;
105  $json = '{"id":1}';
106 
107  $this->config->expects($this->once())
108  ->method('getApiKey')
109  ->with($storeId)
110  ->willReturn('testKey');
111 
112  $this->config->expects($this->once())
113  ->method('getApiUrl')
114  ->with($storeId)
115  ->willReturn(self::$dummy);
116 
117  $this->dataEncoder->expects($this->once())
118  ->method('encode')
119  ->with($this->equalTo($param))
120  ->willReturn($json);
121 
122  $this->client->expects($this->once())
123  ->method('setRawData')
124  ->with($this->equalTo($json), 'application/json')
125  ->willReturnSelf();
126 
127  $client = $this->httpClient->create('url', 'method', $param, $storeId);
128 
129  $this->assertInstanceOf(ZendClient::class, $client);
130  }
131 }