2016-01-06 109 views
0

我正在使用CRUD插件和ADmad的JWT插件在CakePHP 3上开发API。我已经通过导入模式为所有表创建了固定装置,然后定义了一些虚拟记录。现在我想知道测试我的API的最佳方法。测试CakePHP 3 REST API

即:

  1. 如何设置在我的测试中被授权的用户?
  2. 如何在测试框架中调用API方法?

我目前没有任何代码显示,因为我真的不知道如何以正确的方式去解决这个问题。

回答

0

我看到的测试API端点的方法之一是使用IntegrationTestCase套件的post()方法。一个非常基本的例子:访问令牌

public function testLogin() 
{ 
    // You can add this to the setUp() function to make it global 
    $this->configRequest([ 
     'headers' => [ 
      'Accept' => 'application/json', 
      'Content-Type' => 'x-www-form-urlencoded' 
     ] 
    ]); 

    $this->post('/auth/token', ['username' => $username, 'password' => $password]); 
    $this->assertResponseOk(); 
    $this->assertResponseContains('access_token'); 
} 

存储(或预生成一个)&使用该设置授权报头。

您可将授权令牌就像这样(前EVERY要求):

$this->configRequest([ 
     'headers' => [ 
      'Accept' => 'application/json', 
      'Content-Type' => 'x-www-form-urlencoded', 
      'Authorization' => 'Bearer ' . $token 
     ] 
    ]); 

提示:您可以在测试bootstrap.phpConfigure::write()Security.salt值 - 这样的密码腌制的作品!我还发现在你的灯具中保存腌制的密码值很有帮助。

更多详细信息在CakePHP Cookbook