Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send parameter to PHP Unit on the command line

Tags:

php

phpunit

I want to send a parameter to PHP Unit using the command line.

e.g.

./phpunit --foo='bar' AllTests

How can I do this?

The closest I was able to achieve my objective is using the following:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
    <php>
        <env name="foo" value="bar"/>
    </php>
</phpunit>

I can then access the variable using $_ENV['foo'].

However, I want to send this variable using the command line.

like image 646
Yahya Uddin Avatar asked Sep 23 '16 11:09

Yahya Uddin


2 Answers

Using phpunit.xml is obviously for constant environmental variables and using it for passing changing parameters to tests is a bit of an overhead.

What you can do is one of the following (see Passing parameters to PHPUnit for the discussion):

Use setting environmental variables for the command

Example: FOO=bar ./phpunit AllTests

Pros: Trivial.

Cons: Depends on environment; requires remembering names of the variables (which is not that simple if there are many); no obvious documentation on supported/necessary parameters available.

Use $argv for passing parameters and using them inside your test.

Example: ./phpunit AllTests bar

Pros: Trivial; independent from environment; no limitations to PHPUnit parameters.

Cons: Will be a pain if there are more than several arguments, especially if most of them are optional; no obvious documentation for expected arguments.

Use setting environmental variables (and then running tests) with your own runner script/function

Example: . run.sh AllTests bar where run.sh looks at the provided arguments and exports them into the environment.

Pros: Still more or less trivial to implement; adds documentation of the expected argument list; adds error handling (e.g. in case bar is a required parameter, but is not provided).

Cons: PHPUnit parameters inside runner are hardcoded; dependent on the environment.

Fork PHPUnit and implement your own supported parameters in the extended command parser

Example: ./phpunit --foo='bar' AllTests

Pros: Does exactly what you want.

Cons: Not so trivial to implement; requires forking which makes it strongly dependent on CLI of the current PHPUnit version.

Write your own runner with your own command parser

Example: run.sh --foo=bar --coverage-html=baz where run.sh calls some run.php which in its turn runs command arguments through parser, builds the command for running tests and does that.

Pros: Now you can do whatever you like and add any parameters you need. You can implement your own logger, you can run tests in multithread etc.

Cons: Hard to implement; sometimes needs maintenance; is strongly dependent on PHPUnit CLI.

like image 131
BVengerov Avatar answered Nov 15 '22 03:11

BVengerov


You can run any command with environment variable set:

foo=bar ./phpunit AllTests

like image 44
Honza Haering Avatar answered Nov 15 '22 04:11

Honza Haering