Completed
Push — master ( 3f6360...136d46 )
by Gabriel
13s queued 10s
created

StockbaseClientTest::testCreateOrder()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 0
dl 0
loc 64
ccs 47
cts 47
cp 1
crap 2
rs 8.7853
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
namespace Stockbase\Integration\Test\Unit\StockbaseApi\Client;
5
6
use DivideBV\PHPDivideIQ\DivideIQ;
7
use Magento\Sales\Api\Data\OrderInterface;
8
use PHPUnit\Framework\TestCase;
9
use Stockbase\Integration\Model\Config\StockbaseConfiguration;
10
use Stockbase\Integration\StockbaseApi\Client\StockbaseClient;
11
use Stockbase\Integration\StockbaseApi\Client\StockbaseClientException;
12
13
/**
14
 * Class StockbaseClientTest
15
 */
16
class StockbaseClientTest extends TestCase
17
{
18
    /** @var DivideIQ|\PHPUnit_Framework_MockObject_MockObject */
19
    private $divideIqClient;
20
21
    /** @var StockbaseConfiguration|\PHPUnit_Framework_MockObject_MockObject */
22
    private $stockbaseConfiguration;
23
24
    /**
25
     * {@inheritdoc}
26
     */
27 4
    public function setUp()
28
    {
29 4
        $this->divideIqClient = $this->createMock(DivideIQ::class);
30
        
31 4
        $this->stockbaseConfiguration = $this->createMock(StockbaseConfiguration::class);
32 4
    }
33
34
    /**
35
     * testGetStock
36
     */
37 1
    public function testGetStock()
38
    {
39
        $expectedData = [
40 1
            'Since' => 1497797012,
41
            'Until' => 1497797015,
42
        ];
43 1
        $this->divideIqClient->expects($this->once())->method('request')
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in DivideBV\PHPDivideIQ\DivideIQ.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
44 1
            ->with(StockbaseClient::STOCKBASE_STOCK_ENDPOINT, $expectedData, 'GET')
45 1
            ->willReturn('TEST_ANSWER');
46
47 1
        $client = new StockbaseClient($this->divideIqClient, $this->stockbaseConfiguration);
48 1
        $this->assertEquals('TEST_ANSWER', $client->getStock(new \DateTime('@1497797012'), new \DateTime('@1497797015')));
49 1
    }
50
51
    /**
52
     * testGetImages
53
     */
54 1
    public function testGetImages()
55
    {
56
        $expectedData = [
57 1
            'ean' => '101,102,103,104,105',
58
        ];
59
        
60 1
        $this->divideIqClient->expects($this->once())->method('request')
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in DivideBV\PHPDivideIQ\DivideIQ.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
61 1
            ->with(StockbaseClient::STOCKBASE_IMAGES_ENDPOINT, $expectedData, 'GET')
62 1
            ->willReturn('TEST_ANSWER');
63
64 1
        $client = new StockbaseClient($this->divideIqClient, $this->stockbaseConfiguration);
65 1
        $this->assertEquals('TEST_ANSWER', $client->getImages([101, 102, 103, 104, 105]));
66 1
    }
67
68
    /**
69
     * testCreateOrder
70
     */
71 1
    public function testCreateOrder()
72
    {
73 1
        $this->stockbaseConfiguration
74 1
            ->method('getOrderPrefix')
75 1
            ->willReturn('TEST_ORDER_PREFIX');
76
77 1
        $order = $this->createOrderMock();
78
        $reservedItems = $this->createReservedItemMocks();
79 1
        
80 1
        $this->divideIqClient->expects($this->once())->method('request')
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in DivideBV\PHPDivideIQ\DivideIQ.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
81 1
            ->with(
82 1
                StockbaseClient::STOCKBASE_ORDER_REQUEST_ENDPOINT,
83 1
                $this->anything(),
84
                'POST'
85 1
            )
86
            ->willReturnCallback(function ($serviceName, $payload = [], $method = 'GET') use ($order, $reservedItems) {
0 ignored issues
show
Unused Code introduced by
The parameter $method is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
                
88 1
                $this->assertTrue(isset($payload['OrderHeader']['OrderNumber']));
89 1
                $this->assertEquals('TEST_ORDER_PREFIX#'.$order->getRealOrderId(), $payload['OrderHeader']['OrderNumber']);
90 1
                $this->assertTrue(isset($payload['OrderHeader']['TimeStamp']));
91 1
                $this->assertRegExp('/^\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}$/', $payload['OrderHeader']['TimeStamp']);
92 1
                $this->assertTrue(isset($payload['OrderHeader']['Attention']));
93
                $this->assertEquals($order->getCustomerNote(), $payload['OrderHeader']['Attention']);
94 1
95
                $this->assertTrue(isset($payload['OrderLines']));
96 1
                $this->assertCount(count($reservedItems), $payload['OrderLines']);
97 1
                for ($i = 0; $i < count($reservedItems); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
98 1
                    $this->assertEquals($i+1, $payload['OrderLines'][$i]['Number']);
99 1
                    $this->assertEquals($i*100+1, $payload['OrderLines'][$i]['EAN']);
100 1
                    $this->assertEquals($i*100+2, $payload['OrderLines'][$i]['Amount']);
101 1
                    $this->assertEquals(sprintf('%0.2f', ($i*100+3) * 10.95), $payload['OrderLines'][$i]['Price']);
102
                }
103 1
104 1
                $this->assertTrue(isset($payload['OrderDelivery']['Person']['FirstName']));
105
                $this->assertEquals($order->getShippingAddress()->getFirstname(), $payload['OrderDelivery']['Person']['FirstName']);
106 1
                $this->assertTrue(isset($payload['OrderDelivery']['Person']['Surname']));
107 1
                $this->assertEquals($order->getShippingAddress()->getLastname(), $payload['OrderDelivery']['Person']['Surname']);
108 1
                $this->assertTrue(isset($payload['OrderDelivery']['Person']['Company']));
109 1
                $this->assertEquals($order->getShippingAddress()->getCompany(), $payload['OrderDelivery']['Person']['Company']);
110 1
                
111 1
                $this->assertTrue(isset($payload['OrderDelivery']['Address']['Street']));
112
                $this->assertEquals($order->getShippingAddress()->getStreetLine(1), $payload['OrderDelivery']['Address']['Street']);
113 1
                $this->assertTrue(isset($payload['OrderDelivery']['Address']['StreetNumber']));
114 1
                $this->assertEquals($order->getShippingAddress()->getStreetLine(2), $payload['OrderDelivery']['Address']['StreetNumber']);
115 1
                $this->assertTrue(isset($payload['OrderDelivery']['Address']['ZipCode']));
116 1
                $this->assertEquals($order->getShippingAddress()->getPostcode(), $payload['OrderDelivery']['Address']['ZipCode']);
117 1
                $this->assertTrue(isset($payload['OrderDelivery']['Address']['City']));
118 1
                $this->assertEquals($order->getShippingAddress()->getCity(), $payload['OrderDelivery']['Address']['City']);
119 1
                $this->assertTrue(isset($payload['OrderDelivery']['Address']['CountryCode']));
120 1
                $this->assertEquals($order->getShippingAddress()->getCountryId(), $payload['OrderDelivery']['Address']['CountryCode']);
121 1
                
122 1
123
                $response = new \stdClass();
124
                $response->{'StatusCode'} = 1;
125 1
                
126 1
                return $response;
127
            });
128 1
        
129 1
        $client = new StockbaseClient($this->divideIqClient, $this->stockbaseConfiguration);
130
        
131 1
        $result = $client->createOrder($order, $reservedItems);
132
        
133 1
        $this->assertEquals(1, $result->{'StatusCode'});
134
    }
135 1
136 1
    /**
137
     * testCreateOrderApiFail
138
     */
139
    public function testCreateOrderApiFail()
140
    {
141 1
        $this->stockbaseConfiguration
142
            ->method('getOrderPrefix')
143 1
            ->willReturn('TEST_ORDER_PREFIX');
144 1
145 1
        $order = $this->createOrderMock();
146
147 1
        $reservedItems = [];
148
        for ($i = 0; $i < 2; $i++) {
149 1
            $reservedItem = $this->createMock(\Stockbase\Integration\Model\StockItemReserve::class);
150 1
            $reservedItem->method('getEan')->willReturn($i*100+1);
151 1
            $reservedItem->method('getAmount')->willReturn($i*100+2);
152 1
153 1
            $reservedItems[$i] = $reservedItem;
154
        }
155 1
156
        $this->divideIqClient->expects($this->once())->method('request')
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in DivideBV\PHPDivideIQ\DivideIQ.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
157
            ->with(
158 1
                StockbaseClient::STOCKBASE_ORDER_REQUEST_ENDPOINT,
159 1
                $this->anything(),
160 1
                'POST'
161 1
            )
162 1
            ->willReturnCallback(function () {
163
                $item = new \stdClass();
164 1
                $item->{'StatusCode'} = 2;
165 1
                $item->{'ExceptionMessage'} = 'Test exception.';
166 1
                $response = new \stdClass();
167 1
                $response->{'StatusCode'} = 2;
168 1
                $response->{'Items'} = [$item];
169 1
                
170 1
                return $response;
171
            });
172 1
173 1
        $client = new StockbaseClient($this->divideIqClient, $this->stockbaseConfiguration);
174
175 1
        $this->expectException(StockbaseClientException::class);
176
        $this->expectExceptionMessageRegExp('/Test exception\./');
177 1
        
178 1
        $client->createOrder($order, $reservedItems);
179
    }
180 1
    
181
    protected function createOrderMock()
182
    {
183 2
        $shippingAddress = $this->createMock(\Magento\Sales\Model\Order\Address::class);
184
        $shippingAddress->method('getFirstname')->willReturn('TEST_FIRST_NAME');
185 2
        $shippingAddress->method('getLastname')->willReturn('TEST_LAST_NAME');
186 2
        $shippingAddress->method('getCompany')->willReturn('TEST_COMPANY');
187 2
        $shippingAddress->method('getStreetLine')->willReturnCallback(function ($line) {
188 2
            return sprintf('STREET_LINE_%d', $line);
189 2
        });
190 2
        $shippingAddress->method('getPostcode')->willReturn('TEST_ZIP');
191 2
        $shippingAddress->method('getCity')->willReturn('TEST_CITY');
192 2
        $shippingAddress->method('getCountryId')->willReturn('US');
193 2
194 2
        $order = $this->createMock(\Magento\Sales\Model\Order::class);
195
        $order->method('getShippingAddress')->willReturn($shippingAddress);
196 2
197 2
        $order->method('getRealOrderId')->willReturn(123456);
198
        $order->method('getCustomerNote')->willReturn('TEST_CUSTOMER_NOTE');
199 2
200 2
        $order->method('getItemById')->willReturnCallback(function ($orderItemId) {
201
            $orderItem = $this->createMock(\Magento\Sales\Model\Order\Item::class);
202 2
            $orderItem->method('getRowTotal')->willReturn(sprintf('%0.2f', $orderItemId * 10.95));
203
            
204
            return $orderItem;
205
        });
206
        
207
        return $order;
208
    }
209
    
210
    protected function createReservedItemMocks()
211
    {
212
        $reservedItems = [];
213
        for ($i = 0; $i < 2; $i++) {
214
            $reservedItem = $this->createMock(\Stockbase\Integration\Model\StockItemReserve::class);
215
            $reservedItem->method('getEan')->willReturn($i*100+1);
216
            $reservedItem->method('getAmount')->willReturn($i*100+2);
217
            $reservedItem->method('getOrderItemId')->willReturn($i*100+3);
218
219
            $reservedItems[$i] = $reservedItem;
220
        }
221
        
222
        return $reservedItems;
223
    }
224
}
225