【问题标题】:Phpunit Testing Controller only unauthorized symfony 3.4Phpunit 测试控制器仅未经授权的 symfony 3.4
【发布时间】:2018-12-13 21:06:38
【问题描述】:

我正在尝试测试我的控制器,但由于某种原因,收到的唯一状态码是 UNAUTHORIZED。我不确定是什么问题,所以我希望有人能帮帮我。我正在使用 SYmfony 3.4,这是我的代码:

loginFormAuth:

protected function login(array $roles = ['ROLE_USER'])
{
    $session = $this->client->getContainer()->get('session');

    $firewallContext = 'api';

    $token = new UsernamePasswordToken('test', null, $firewallContext, $roles);
    $session->set('_security_' . $firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);
}

protected function requestUrl($url)
{
    return $this->client->request('GET', $url);
}


public function testGetProductsAsAdmin()
{
    $this->logIn(array('ROLE_ADMIN');

    $url = 'api/products';
    $this->getUrl($url);

    $this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
}


public function getProductAction(Request $request, ListProductService $service)
{
    $this->checkAccess($this->getUser()); // so here only the admin has permission

    $result = $service->execute();

    return new Response($this->serializer->serialize($result));
}

security.yml

access_control:
    - { path: ^/api/products, roles: ROLE_ADMIN }

有什么建议吗?

【问题讨论】:

  • 查看 symfony 工具栏时你看到了什么角色?
  • 不知道去哪里找。调试不起作用,并且在控制台中它没有说这样的话。仅返回 401 而不是 200。

标签: symfony controller phpunit


【解决方案1】:

我在上面注意到的一件事是,在函数中:testGetProductsAsAdmin(),你调用了一个函数:$this->getUrl($url); 在你列出的代码中看不到那个函数,你想调用吗

$this->requestUrl($url);?

还有一个问题,return $this->client->request('GET', $url);您是否缺少此请求中的令牌?

【讨论】:

  • 是的,该函数调用 $this->client->request('GET', $url);
  • 好的,在你的测试中,你调用了正确的方法:$this->requestUrl($url),然后你能断言 200 响应吗?
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 2014-02-10
  • 2019-01-14
  • 2015-03-24
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多