Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
JsonEncodedTest.php
Go to the documentation of this file.
1 <?php
8 
10 
11 class JsonEncodedTest extends \PHPUnit\Framework\TestCase
12 {
16  private $model;
17 
21  private $attributeMock;
22 
26  private $serializerMock;
27 
31  protected function setUp()
32  {
33  $this->serializerMock = $this->getMockBuilder(\Magento\Framework\Serialize\Serializer\Json::class)
34  ->disableOriginalConstructor()
35  ->setMethods(['serialize', 'unserialize'])
36  ->getMock();
37 
38  $this->serializerMock->expects($this->any())
39  ->method('serialize')
40  ->will(
41  $this->returnCallback(
42  function ($value) {
43  return json_encode($value);
44  }
45  )
46  );
47 
48  $this->serializerMock->expects($this->any())
49  ->method('unserialize')
50  ->will(
51  $this->returnCallback(
52  function ($value) {
53  return json_decode($value, true);
54  }
55  )
56  );
57 
58  $this->attributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class)
59  ->disableOriginalConstructor()
60  ->setMethods(['getAttributeCode'])
61  ->getMock();
62 
63  $this->attributeMock->expects($this->any())
64  ->method('getAttributeCode')
65  ->will($this->returnValue('json_encoded'));
66 
67  $this->model = new JsonEncoded($this->serializerMock);
68  $this->model->setAttribute($this->attributeMock);
69  }
70 
74  public function testBeforeSave()
75  {
76  $product = new \Magento\Framework\DataObject(
77  [
78  'json_encoded' => [1, 2, 3]
79  ]
80  );
81  $this->model->beforeSave($product);
82  $this->assertEquals(json_encode([1, 2, 3]), $product->getData('json_encoded'));
83  }
84 
89  {
90  $product = new \Magento\Framework\DataObject(
91  [
92  'json_encoded' => [1, 2, 3]
93  ]
94  );
95 
96  // save twice
97  $this->model->beforeSave($product);
98  $this->model->beforeSave($product);
99 
100  // check it is encoded only once
101  $this->assertEquals(json_encode([1, 2, 3]), $product->getData('json_encoded'));
102  }
103 
107  public function testAfterLoad()
108  {
109  $product = new \Magento\Framework\DataObject(
110  [
111  'json_encoded' => json_encode([1, 2, 3])
112  ]
113  );
114  $this->model->afterLoad($product);
115  $this->assertEquals([1, 2, 3], $product->getData('json_encoded'));
116  }
117 
122  {
123  $product = new \Magento\Framework\DataObject(
124  [
125  'json_encoded' => null
126  ]
127  );
128  $this->model->afterLoad($product);
129  $this->assertEquals([], $product->getData('json_encoded'));
130  }
131 }
$value
Definition: gender.phtml:16