[英]Zend Framework 2 - UnitTests
I want to create a simple access unit test like it is shown in the tutorial . 我想创建一个简单的访问单元测试,如教程中所示。
My project uses ZFCUser
for authentication. 我的项目使用
ZFCUser
进行身份验证。
As a result my (obviously not authenticated) tester get a HTTP response
of 302 and not the expected 200. 结果,我的(显然未经过身份验证的)测试人员得到的
HTTP response
为302而不是预期的200。
Any ideas what I can do about it? 有什么想法我可以做些什么呢? Thanks!
谢谢!
The code from the tutorial looks like this: 教程中的代码如下所示:
public function testAddActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'add');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
thanks, good idea! is there an easy way to mock the auth? – Ron
I'm posting this as an answer, because its too much to press it into a comment. 我将此作为答案发布,因为将其压入评论中太过分了。 Yes, there is an easy way to mock the AuthenticationService class.
是的,有一种简单的方法来模拟AuthenticationService类。 First of all, check the docs on Stubs / Mocks .
首先,检查Stubs / Mocks上的文档。
What you need to do is to create the mock from Zend\\Authentication\\AuthenticationService and configure it to pretend to contain an identity. 您需要做的是从Zend \\ Authentication \\ AuthenticationService创建模拟并将其配置为假装包含标识。
public function testSomethingThatRequiresAuth()
{
$authMock = $this->getMock('Zend\Authentication\AuthenticationService');
$authMock->expects($this->any())
->method('hasIdentity')
->will($this->returnValue(true));
$authMock->expects($this->any())
->method('getIdentity')
->will($this->returnValue($identityMock));
// Assign $authMock to the part where Authentication is required.
}
In this example, a variable $identityMock
is required to be defined previously. 在此示例中,需要先定义变量
$identityMock
。 It could be a mock of your user model class or something like that. 它可能是您的用户模型类的模拟或类似的东西。
Note that I haven't tested it, so it might not work instantly. 请注意,我还没有测试过,所以它可能无法立即生效。 However, its just supposed to show you the direction.
然而,它只是想向你展示方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.