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


namespace yiiunit\framework\helpers;

use yii\helpers\Json;
Alexander Makarov committed
7
use yii\test\TestCase;
Qiang Xue committed
8
use yii\web\JsExpression;
9

Alexander Makarov committed
10
class JsonTest extends TestCase
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
{
	public function testEncode()
	{
		// basic data encoding
		$data = '1';
		$this->assertSame('"1"', Json::encode($data));

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

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

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

		// complex data
		$expression1 = 'function (a) {}';
		$expression2 = 'function (b) {}';
		$data = array(
			'a' => array(
39
				1, new JsExpression($expression1)
40
			),
41
			'b' => new JsExpression($expression2),
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
		);
		$this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data));
	}

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

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

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