<?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方式错了,逐一排查。