Symfony 3 PhpUnit 提交表单

3

我尝试使用以下代码在我的管理后台测试PHP表单:

    $client = $this->createAuthorizedClient();
    $crawler = $client->request('GET', '/user/edit/1');

    $form = $crawler->selectButton('Save')->form();
    $form['sf_guard_user[lastName]']  = 'lastname';
    $crawler = $client->submit($form);
    $form->get('sf_guard_user[lastName]')->setValue('Richardson');
    $client->submit($form);
    $response = $client->getResponse();

我的函数createAuthorizedClient在这里:

    protected function createAuthorizedClient()
{
    $client = static::createClient();
    $container = $client->getContainer();

    $session = $container->get('session');
    $userManager = $container->get('fos_user.user_manager');
    $loginManager = $container->get('fos_user.security.login_manager');
    $firewallName = $container->getParameter('fos_user.firewall_name');

    $user = $userManager->findUserByUsername('ASSELIN');
    $loginManager->logInUser($firewallName, $user);

    $container->get('session')->set('_security_' . $firewallName,
        serialize($container->get('security.token_storage')->getToken()));
    $container->get('session')->save();
    $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

    return $client;
}

但是当我启动我的测试时,$response中出现了以下错误:
{"code":500,"message":"A Token was not found in the TokenStorage."}"

完整的堆栈跟踪在这里:
    Symfony\Component\HttpFoundation\Response {#2362
        +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#2372
            #computedCacheControl: array:1 [
            "no-cache" => true
        ]
        #cookies: []
        #headerNames: array:3 [
          "cache-control" => "Cache-Control"
          "content-type" => "Content-Type"
          "allow" => "Allow"
        ]
        #headers: array:3 [
          "cache-control" => array:1 [
                0 => "no-cache"
            ]
          "content-type" => array:1 [
                0 => "application/json;"
            ]
          "allow" => array:1 [
                0 => "PUT"
            ]
        ]
        #cacheControl: []
      }
      #content: "{"code":500,"message":"A Token was not found in the TokenStorage."}"
      #version: "1.1"
      #statusCode: 500
      #statusText: "Internal Server Error"
      #charset: "UTF-8"
    }

我尝试寻找解决方案,但我不理解为什么会出现这个错误。能否向我解释一下我的错误?该表单是直接使用put方法提交到api中的。

最好的问候,

Benoit


恭喜,您刚刚发现了为什么服务定位器是反模式的原因。;-) - Jakub Matczak
你是否在源代码中使用grep查找“在TokenStorage中未找到令牌”以了解所触发的逻辑? - Steve
源代码在上面。它是$response的结果。 - Bostak
异常来自AuthenticationListener,告诉您请求的令牌未找到。这暗示您的会话未保存。这可能是由于config.yml中配置错误的会话或者security.yml存在问题,例如stateless: true?您是否检查过在调用$session->save()后是否编写了会话文件? - dbrumann
我检查了我的security.yml文件,发现stateless设置为true。我尝试在我的会话中写入一些内容,例如$container->get('session')->set('test', 'toto'); 当我验证会话测试存在并且值正确时,“toto”。 - Bostak
1个回答

0

我通过在我的security.yml文件中添加http_basic来解决了我的问题:

security:
    firewalls:
        wsse_secured:
            stateless: false
            http_basic: ~

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接