Reputation: 26137
I haven't found any description how to inject external data into TestCases in phpunit. My goal is to set a workspace directory in the xml config file and read the path of that from every class. Now I can solve this only with global variable, which is disgusting:
In bootstrap:
global $workspace;
$workspace = __DIR__ . '/../test/WorkSpace/';
In the tests:
class MyTest extends PHPUnit_Framework_TestCase
{
protected $workSpace;
public function __construct()
{
global $workspace;
$this->workSpace = $workspace;
parent::__construct();
}
//...
}
The config xml for that:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://phpunit.de/phpunit.xsd"
backupGlobals="false"
verbose="true"
bootstrap="Application/bootstrap.php">
<testsuites>
<testsuite name="PHPUnit">
<directory>test</directory>
</testsuite>
</testsuites>
</phpunit>
Upvotes: 1
Views: 718
Reputation: 13759
You should avoid using globals. For this purpose, you can define constants in your bootstrap file.
Im reviewing the documentation and I've found that you can define PHP values in your XML file.
Setting PHP INI settings, Constants and Global Variables
The element and its children can be used to configure PHP settings, constants, and global variables. It can also be used to prepend the include_path.
<php>
<includePath>.</includePath>
<ini name="foo" value="bar"/>
<const name="foo" value="bar"/>
<var name="foo" value="bar"/>
<env name="foo" value="bar"/>
<post name="foo" value="bar"/>
<get name="foo" value="bar"/>
<cookie name="foo" value="bar"/>
<server name="foo" value="bar"/>
<files name="foo" value="bar"/>
<request name="foo" value="bar"/>
</php>
The XML configuration above corresponds to the following PHP code:
ini_set('foo', 'bar');
define('foo', 'bar');
$GLOBALS['foo'] = 'bar';
$_ENV['foo'] = 'bar';
$_POST['foo'] = 'bar';
$_GET['foo'] = 'bar';
$_COOKIE['foo'] = 'bar';
$_SERVER['foo'] = 'bar';
$_FILES['foo'] = 'bar';
$_REQUEST['foo'] = 'bar';
As I've said above, I'd recommend you to use constants using define, instead of global variables.
Upvotes: 3