测试REST get请求
如何使用phpunit4.1测试restapi的GET请求?我使用Slim PHP框架,可以测试响应代码,但不能测试正文或标题。 这就是我到目前为止所做的: 测试类:测试REST get请求,rest,phpunit,slim,Rest,Phpunit,Slim,如何使用phpunit4.1测试restapi的GET请求?我使用Slim PHP框架,可以测试响应代码,但不能测试正文或标题。 这就是我到目前为止所做的: 测试类: class AssetTest extends PHPUnit_Framework_TestCase { public function request($method, $path, $options = array()) { // Capture STDOUT ob_start(); // Prep
class AssetTest extends PHPUnit_Framework_TestCase
{
public function request($method, $path, $options = array())
{
// Capture STDOUT
ob_start();
// Prepare a mock environment
Environment::mock(array_merge(array(
'REQUEST_METHOD' => $method,
'PATH_INFO' => $path,
'SERVER_NAME' => 'slim-test.dev',
), $options));
$app = new \Slim\Slim();
$this->app = $app;
$this->request = $app->request();
$this->response = $app->response();
// Return STDOUT
return ob_get_clean();
}
public function get($path, $options = array()){
$this->request('GET', $path, $options);
}
public function testGetAssets(){
$this->get('/asset');
$this->assertEquals('200', $this->response->status());
}
}
如果的JSON响应如下所示(代码200):
一切都很好。要获得响应的主体,只需调用
$response->getBody()
并使用json\u decode
解码此响应。要获取标题,请调用$response->getHeaders()
在您的情况下,它将通过$this->response->getBody()
实现。那你的测试呢
方法如下所示
public function testGetAssets(){
$this->get('/asset');
$response = json_decode($this->response->getBody(), true); //response body
$headers = $this->response->getHeaders() //response headers
$this->assertEquals('200', $this->response->status());
}
这个答案是关于guzzlehttp的最新版本,即6.0您确定要进行单元测试吗?这是关于测试单元,而不是功能。在这种情况下,您可能需要测试您的操作功能(您的
$app->get('\some\url',$actionMethod)中的$actionMethod
)
。REST API的功能测试可以也应该手动完成,因为没有很好的自动工具。但是你可以尝试SoapUI之类的工具。好的,那么你的意思是测试模型功能,例如进行数据库查询?是的,这将是一个很好的开始。如果你有一些中间件,你也可以测试它。
public function testGetAssets(){
$this->get('/asset');
$response = json_decode($this->response->getBody(), true); //response body
$headers = $this->response->getHeaders() //response headers
$this->assertEquals('200', $this->response->status());
}