问题
I'm currently trying to write an integration test for some controller whereby it is necessary to send an authentication header. In my controller I have some actions made public accessible through the following code:
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
}
.....
}
Now I have an integration test case in which I want to allow that all actions are possible to access without authentication. Is there any simple way to make this possible?
Integration case code:
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();
}
}
回答1:
Generally it's possible to manipulate the controller in an overriden \Cake\TestSuite\IntegrationTestCase::controllerSpy()
method, like
public function controllerSpy($event)
{
parent::controllerSpy($event);
if (isset($this->_controller)) {
$this->_controller->Auth->allow();
}
}
but as already mentioned in the comments, it would be better to properly authenticate your requests instead!
While integration tests do not necessarily have to be black-box tests, peering into the internals of the test subject isn't an overly good idea. Mocking certain parts in an integration test might be reasonable when you are looking for something in between "test everything" and "test units", ie larger groups of modules, but that should mostly only be necessary when heavy complexity is involved in a request.
See also
- API > \Cake\TestSuite\IntegrationTestCase::controllerSpy()
- API > \Cake\TestSuite\IntegrationTestCase::$_controller
来源:https://stackoverflow.com/questions/35958132/allow-all-actions-for-authentication-in-integration-test-cakephp