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


namespace yiiunit\framework\helpers;

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

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

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

		// simple object encoding
		$data = new \stdClass();
Alexander Makarov committed
29 30
		$data->a = 1;
		$data->b = 2;
31 32 33 34
		$this->assertSame('{"a":1,"b":2}', Json::encode($data));

		// expression encoding
		$expression = 'function () {}';
35
		$data = new JsExpression($expression);
36 37 38 39 40
		$this->assertSame($expression, Json::encode($data));

		// complex data
		$expression1 = 'function (a) {}';
		$expression2 = 'function (b) {}';
Alexander Makarov committed
41 42
		$data = [
			'a' => [
43
				1, new JsExpression($expression1)
Alexander Makarov committed
44
			],
45
			'b' => new JsExpression($expression2),
Alexander Makarov committed
46
		];
47
		$this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data));
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 58 59 60 61
	}

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

		// array decoding
		$json = '{"a":1,"b":2}';
Alexander Makarov committed
62
		$this->assertSame(['a' => 1, 'b' => 2], Json::decode($json));
63 64 65 66 67 68

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