Passing parameters to PHPUnit

Viewed 35401

I'm starting to write PHPUnit tests and I'd like the tests to be run from developers machines as well as from our servers. Developers machines are set up differently than the servers and even differently from each other.

To run in these different places it seems to be the person that runs the test is going to have to indicate where it's being run. The test can then look up the proper config of the machine it's running on.

I'm imagining something like:

phpunit.bat -X johns_laptop unittest.php

or on the alpha server:

phpunit -X alpha unittest.php

In the test I would be able to get the value if the 'X' (or whatever it is) parameter and know, for example, what the path to the app root is for this machine.

It doesn't look like the command line allows for that - or have I missed something?

10 Answers

One way would be for you to inspect $argv and $argc. Something like:

<?php

require_once 'PHPUnit/Framework/TestCase.php';

class EnvironmentTest extends PHPUnit_Framework_TestCase {
    public function testHasParam() {
            global $argv, $argc;
            $this->assertGreaterThan(2, $argc, 'No environment name passed');
            $environment = $argv[2];
    }
}

Then you can call your phpunittest like this:

phpunit EnvironmentTest.php my-computer

No need of environment variables nor special scripts. You can use -d option to set php.ini values.

<?php // tests/IniTest.php
use PHPUnit\Framework\TestCase;

class IniTest extends TestCase
{
  public $server;

  public function setUp(): void
  {
    $this->server = ini_get('my.custom.server') ?: '127.0.0.1'; // fallback
  }

  public function testDummy()
  {
    $this->assertIsString($this->server);
  }
}

Execute the code like this:

vendor/bin/phpunit -d my.custom.server=192.168.1.15 tests/IniTest.php

Setting custom php.ini values is valid. For example you can configure a PDO connection alias with pdo.dsn.*. https://www.php.net/manual/en/pdo.construct.php

If you would like to run tests on remote machine, use ssh then run it. On locale machine you only have to cd to your root dir, then run phpunit.

user@local:/path/to/your/project$ phpunit
user@remote:/var/www/project$ phpunit

Edit: You are talking about a machine dependent configuration. (What kind of conf btw?) My solution is to put these config under the same, not versioncontrolled place, then read/parse it runtime, in the needed set up methds for example.

Related