<?php
namespace app\tests;
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client;
class UserTest extends TestCase
{
private $client;
public function setUp()
{
$this->client = new \GuzzleHttp\Client( [
'base_uri' => 'http://z.slim.com',
'http_errors' => false,
]);
}
public function testUser()
{
$response = $this->client->get('/user/vilay');
$this->assertEquals(200, $response->getStatusCode());
$body = $response->getBody();
$data = json_decode($body, true);
$this->assertArrayHasKey('code', $data);
$this->assertArrayHasKey('msg', $data);
$this->assertArrayHasKey('data', $data);
$this->assertEquals(0, $data['code']);
}
}
寫完測試程式碼之後,執行
php vendor/bin/phpunit app/tests/UserTest.php
沒有執行到測試,直接把phpunit腳本輸出了
dir=$(d=${0%[/\]*}; cd "$d"; cd "../phpunit/phpunit" && pwd)
# See if we are running in Cygwin by checking for cygpath program
if command -v 'cygpath' >/dev/null 2>&1; then
# Cygwin paths start with /cygdrive/ which will break windows PHP,
# so we need to translate the dir path to windows format. However
# we could be using cygwin PHP which does not require this, so we
# test if the path to PHP starts with /cygdrive/ rather than /usr/bin
if [[ $(which php) == /cygdrive/* ]]; then
dir=$(cygpath -m "$dir");
fi
fi
dir=$(echo $dir | sed 's/ /\ /g')
"${dir}/phpunit" "$@"
另外,我把單元測試配置到系統環境變數裡面,執行測試
phpunit app/tests/UserTest.php
需要在程式碼頭部引入autoload.php
#
require_once 'vendor/autoload.php';
沒辦法自動載入的嗎
已解決,在前面兩位朋友的答案提示下,自己找到了解決方法
網路找些教學很多都是用指令執行
可能是因為版本原因,早期的版本是php腳本文件,我的版本是
"phpunit/phpunit": "^6.2"
,vendor/bin/phpunit
是個shell腳本文件,(沒有用過5. x的具體我也不知道)。正確使用方式是,給予腳本檔案可執行權限
執行測試
自動載入方式實作了,使用composer載入的phpunit元件包,在專案的根目錄中有個phpunit.xml,可以在裡面設定自動載入的路徑
你可以在框架外,隨便寫一個單元測試文件,使用phpunit xxx.php 測試一下,這樣就知道是否phpunit安裝正常,是否引入autoload.php方式錯了,逐一排查。