JsonTest.php 1.81 KB
Newer Older
1 2 3 4 5
<?php

namespace yiiunit\framework\helpers;

use yii\helpers\Json;
6
use yiiunit\TestCase;
Qiang Xue committed
7
use yii\web\JsExpression;
8

9 10 11
/**
 * @group helpers
 */
Alexander Makarov committed
12
class JsonTest extends TestCase
13
{
14 15 16 17 18
    public function testEncode()
    {
        // basic data encoding
        $data = '1';
        $this->assertSame('"1"', Json::encode($data));
19

20 21 22 23 24
        // simple array encoding
        $data = [1, 2];
        $this->assertSame('[1,2]', Json::encode($data));
        $data = ['a' => 1, 'b' => 2];
        $this->assertSame('{"a":1,"b":2}', Json::encode($data));
25

26 27 28 29 30
        // simple object encoding
        $data = new \stdClass();
        $data->a = 1;
        $data->b = 2;
        $this->assertSame('{"a":1,"b":2}', Json::encode($data));
31

32 33 34 35
        // expression encoding
        $expression = 'function () {}';
        $data = new JsExpression($expression);
        $this->assertSame($expression, Json::encode($data));
36

37 38 39 40 41 42 43 44 45 46
        // complex data
        $expression1 = 'function (a) {}';
        $expression2 = 'function (b) {}';
        $data = [
            'a' => [
                1, new JsExpression($expression1)
            ],
            'b' => new JsExpression($expression2),
        ];
        $this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data));
47

48 49 50 51
        // https://github.com/yiisoft/yii2/issues/957
        $data = (object) null;
        $this->assertSame('{}', Json::encode($data));
    }
52

53 54 55 56 57
    public function testDecode()
    {
        // basic data decoding
        $json = '"1"';
        $this->assertSame('1', Json::decode($json));
58

59 60 61
        // array decoding
        $json = '{"a":1,"b":2}';
        $this->assertSame(['a' => 1, 'b' => 2], Json::decode($json));
62

63 64 65 66 67
        // exception
        $json = '{"a":1,"b":2';
        $this->setExpectedException('yii\base\InvalidParamException');
        Json::decode($json);
    }
Zander Baldwin committed
68
}