TestCase.php 1.66 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php

Qiang Xue committed
3 4
namespace yiiunit;

5 6 7 8 9
require_once('PHPUnit/Runner/Version.php');
spl_autoload_unregister(['Yii', 'autoload']);
require_once('PHPUnit/Autoload.php');
spl_autoload_register(['Yii', 'autoload']); // put yii's autoloader at the end

Carsten Brandt committed
10 11 12
/**
 * This is the base class for all yii framework unit tests.
 */
13
abstract class TestCase extends \PHPUnit_Framework_TestCase
w  
Qiang Xue committed
14
{
Qiang Xue committed
15
	public static $params;
w  
Qiang Xue committed
16

Carsten Brandt committed
17 18 19 20
	/**
	 * Clean up after test.
	 * By default the application created with [[mockApplication]] will be destroyed.
	 */
21 22 23
	protected function tearDown()
	{
		parent::tearDown();
Carsten Brandt committed
24
		$this->destroyApplication();
25
	}
Carsten Brandt committed
26 27 28 29 30 31 32 33

	/**
	 * Returns a test configuration param from /data/config.php
	 * @param string $name params name
	 * @param mixed $default default value to use when param is not set.
	 * @return mixed the value of the configuration param
	 */
	public function getParam($name, $default = null)
w  
Qiang Xue committed
34
	{
35 36
		if (static::$params === null) {
			static::$params = require(__DIR__ . '/data/config.php');
w  
Qiang Xue committed
37
		}
38
		return isset(static::$params[$name]) ? static::$params[$name] : $default;
w  
Qiang Xue committed
39
	}
Carsten Brandt committed
40 41 42 43 44

	/**
	 * Populates Yii::$app with a new application
	 * The application will be destroyed on tearDown() automatically.
	 * @param array $config The application configuration, if needed
Alexander Makarov committed
45
	 * @param string $appClass name of the application class to create
Carsten Brandt committed
46
	 */
Alexander Makarov committed
47
	protected function mockApplication($config = [], $appClass = '\yii\console\Application')
48
	{
Alexander Makarov committed
49
		static $defaultConfig = [
50 51
			'id' => 'testapp',
			'basePath' => __DIR__,
Alexander Makarov committed
52
		];
53

Alexander Makarov committed
54
		new $appClass(array_merge($defaultConfig, $config));
55
	}
56

Carsten Brandt committed
57 58 59 60
	/**
	 * Destroys application in Yii::$app by setting it to null.
	 */
	protected function destroyApplication()
61
	{
62
		\Yii::$app = null;
63
	}
Zander Baldwin committed
64
}