将变量传递给 PhpUnit

2022-01-25 00:00:00 php phpunit

我使用 phpunit 开发了一组测试用例,用于测试开发站点和生产站点.唯一的区别是域名.如何将域从命令行传递到 phpunit 测试用例,这样我就不需要修改每个文件?

I developed a set of test cases using phpunit used for testing both development site and the production site. The only difference is the domain name. How can I pass the domain from command line to phpunit test cases so that I do not need to modify every file?

推荐答案

在你的 phpunit-bootstrap.php 你可以这样做:

In your phpunit-bootstrap.php you can do something like this:

$site = getenv('DOMAIN');

并使用

<php>
  <env name="DOMAIN" value="http://production.com"/>
</php>

在您的 phpunit.xml 文件中 如文档中所示.

in your phpunit.xml file as shown in the documentation.

这种方法的缺点是您需要有两个不同的 xml 文件.

The downside of this approach is that you need to have two different xml files.

其他选项在 phpunit 周围使用自定义包装脚本,如 @DavidHarkness 所展示的,这往往效果很好

Other options are using a custom wrapper script around phpunit like @DavidHarkness showed which tends to work out well

或者,如果您不想以自动化方式(或同时使用这两种方法)运行这些测试来执行以下操作:

or, if you don't want to run those tests in an automated way (or use both approaches) to do something like:

$site = getenv('DOMAIN');
if(!$site) {
    echo "Enter Domain: ";
    $site = fgets(STDIN);
}

让跑步者检查环境,如果没有,请询​​问您的域.

and have the runner check the environment and if nothing is there ask you for the domain.

几乎所有 php 可以从外部世界获取输入的方式都是如此.

The same goes for pretty much every way that php can take in input from the outside world.

<php>
  <define name="DOMAIN" value="http://production.com"/>
</php>

例如,在您使用常量的情况下也可以使用.

also works in case you are using a constant anyways, for example.

相关文章