cakephp 控制器测试 - 如何测试需要授权的操作?
标题几乎说明了一切。我想测试例如 UsersController::admin_index()
操作,但需要授权用户访问此位置,因此当我运行测试时,它会将我发送到登录页面,甚至当我手动登录时,没有进行任何测试。
那么如何在不编辑实际授权码的情况下强制蛋糕跳过授权呢?
顺便说一句,如果有帮助的话,我的 testAdminIndex()
代码如下所示:
function testAdminIndex() {
$result = $this->testAction('/admin/users/index');
debug($result);
}
The title pretty much says it all. I would like to test e.g. UsersController::admin_index()
action, but it's required for the user to be authorized to access this location, therefore when I run the test it sends me to the login page and even when I log in manully, no tests are done.
So how can I force cake to skip authorization without editing the actual authorization code?
btw, in case it helps, my testAdminIndex()
code looks like this:
function testAdminIndex() {
$result = $this->testAction('/admin/users/index');
debug($result);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一篇文章介绍了这个主题...
http: //mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way
建议在为经过身份验证的用户添加会话值后完全绕过“testAction”并手动执行请求。示例如下...
There's an article that covers the subject here ...
http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way
The recommendation is to bypass "testAction" completely and manually perform the request, after adding session values for the authenticated user. The example is as follows ...
这是在 cakephp 测试文档上。
http://book.cakephp.org /3.0/en/development/testing.html#testing-actions-that-require-authentication
测试需要身份验证的操作
如果您使用 AuthComponent,则需要删除 AuthComponent 用于验证用户身份的会话数据。您可以使用 IntegrationTestCase 中的辅助方法来执行此操作。假设您有一个包含 add 方法的 ArticlesController,并且该 add 方法需要身份验证,您可以编写以下测试:
我使用了这个,
我实际上有角色,所以我的解决方案如下所示:
This is on the cakephp testing documentation.
http://book.cakephp.org/3.0/en/development/testing.html#testing-actions-that-require-authentication
Testing Actions That Require Authentication
If you are using AuthComponent you will need to stub out the session data that AuthComponent uses to validate a user’s identity. You can use helper methods in IntegrationTestCase to do this. Assuming you had an ArticlesController that contained an add method, and that add method required authentication, you could write the following tests:
I used this
I actually have roles so my solution looks like this: