允许集成测试 cakephp 中的所有身份验证操作

Allow all actions for authentication in integration test cakephp

我目前正在尝试为某些控制器编写集成测试,因此有必要发送身份验证 header。在我的控制器中,我有一些操作可以通过以下代码 public 访问:

namespace App\Controller\Api;

use Cake\Event\Event;
use Cake\Network\Exception\UnauthorizedException;
use Cake\Utility\Security;
use Firebase\JWT\JWT;

class UsersController extends AppController
{
   public function initialize()
   {
       parent::initialize();
       $this->Auth->allow(['add', 'token']); // public methods
   }
  .....
}

现在我有一个集成测试用例,我想在其中允许无需身份验证即可访问所有操作。有什么简单的方法可以做到这一点吗?

集成案例代码:

namespace App\Test\TestCase\Controller;

use App\Controller\Api\UsersController;
use Cake\TestSuite\IntegrationTestCase;

class ApiPicturesControllerTest extends IntegrationTestCase{
   public $fixtures = [
      'app.albums',
      'app.pictures',
      'app.users',
      'app.comments',
      'app.users_albums'
   ];
   public function setUp(){
       parent::setUp();
       // Allow all actions
       // $this->Auth->allow();
   }
   public function testViewShouldPass(){
        $this->configRequest([
           'headers' => [
               'Accept' => 'application/json'
           ]
        ]);
        $data = $this->get('/api/pictures/1.json');
        $this->assertResponseOk();
    }
}

通常可以在覆盖的 \Cake\TestSuite\IntegrationTestCase::controllerSpy() 方法中操纵控制器,例如

public function controllerSpy($event)
{
    parent::controllerSpy($event);

    if (isset($this->_controller)) {
        $this->_controller->Auth->allow();
    }
}

但是正如评论中已经提到的那样,最好对您的请求进行正确的身份验证!

虽然集成测试不一定是黑盒测试,但窥探测试对象的内部并不是一个好主意。当您正在寻找介于 "test everything" 和 "test units" 之间的东西时,在集成测试中模拟某些部分可能是合理的,即更大的模块组,但只有在涉及大量复杂性时才应该这样做请求。

另见