我想测试我的 php 代码,我决定使用 PHPUnit 进行测试。
我已按照 official documentation 的步骤进行操作
$ wget https://phar.phpunit.de/phpunit.phar
$ chmod +x phpunit.phar
$ sudo mv phpunit.phar /usr/local/bin/phpunit
$ phpunit --version
PHPUnit x.y.z by Sebastian Bergmann and contributors.
但我在 MacOS X 上使用 MAMP。
所以我不确定如何在 MAMP 中实现 PHAR 文件。
通常,文档告诉我们在终端中使用这个注释:
sudo mv phpunit.phar /usr/local/bin/phpunit
我的 PHP 位置是:
/Applications/MAMP/bin/php/php5.2.17/bin/
我试过运行这条评论:
sudo mv phpunit.phar /Applications/MAMP/bin/php/php5.2.17/bin/
我不知道我应该在这一步做什么。请看一下,因为它不起作用。
最佳答案
以下是我用来成功让 PHPUnit 在 MAMP 中工作的步骤。这些说明 从不同的地方拼凑而成。我希望将所有内容集中在一个地方会有所帮助 其他人。测试愉快!
在终端中使用 MAMP 的 PHP
改编自 How to override the path of PHP to use the MAMP path?
使用以下行编辑或创建 ~/.bash_profile
# Use MAMP's latest version of PHP
MAMP_LATEST_PHP=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
export PATH=/Applications/MAMP/bin/php/${MAMP_LATEST_PHP}/bin:$PATH
将这些行放在导出 $PATH 的任何其他行之后 - 这可确保您的 MAMP PHP 在路径中最先找到。请注意,这些行试图在您的 MAMP 安装中找到编号最高的 PHP 版本。如果需要,请随意将其调整为您拥有的特定版本。
当您从终端中的 which php
获取 MAMP 路径时,您可以说您做对了。你应该得到这样的东西:
/Applications/MAMP/bin/php/php7.0.0/bin/php
安装PHPUnit
大多数情况下,这是从 PHPUnit 网站下载 PHP 存档 (PHAR)。有一些方法可以从我无法开始工作的命令行执行此操作。所以,我使用了网络浏览器。
- 从 https://phar.phpunit.de 下载最新的 PHPUnit PHAR
- 将其移动到
/usr/local/bin
cd/usr/local/bin
- 使用
chmod +x phpunit-5.3.2.phar
使其可执行(根据实际名称调整) - 用
ln -s phpunit-5.3.2.phar ./phpunit
做一个符号链接(symbolic link)(根据实际名称调整) - 使用
phpunit --version
检查版本
你应该得到这样的东西:
Sebastian Bergmann 和贡献者的 PHPUnit 5.3.2。
在步骤 5 中构建符号链接(symbolic link)允许您使用 phpunit
而不必键入
phpunit-5.3.2.phar
代替。它还允许您无需更新 PHPUnit
更改您键入的内容,当然假设您在创建时创建了一个新的符号链接(symbolic link)
更新。
编写测试
这不是一个详尽的部分。关于编写测试有更好的教程。 相反,这只是我对规则的一些经验,让我感到困惑, 尽管我相信其他人都知道他们:
- 您的测试类名称必须以 Test 结尾:
类 SomeTest 扩展了 PHPUnit_Framework_TestCase
- 您的测试类文件名必须以 Test.php 结尾并匹配包含的类:
SomeTest.php
- 测试类中要作为测试运行的方法名称必须以 test 开头:
公共(public)函数 testSomething()
运行测试
此时,它应该很简单:
phpunit SomeTest
如果一切顺利,PHPUnit 将运行您的测试并为您提供结果。
添加方便的别名
假设一切正常(耶!)在你的 ~/.bash_profile
中尝试这个别名
# Use colors when running phpunit
alias phpunit='phpunit --colors'
关于php - 如何使用 PHAR 在 MAMP 中配置 PHPUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28510488/