Symfony 3 PhpUnit提交表格

时间:2016-09-06 15:35:10

标签: php testing phpunit symfony

我尝试使用以下代码在我的管理员中测试我的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"
    }

我试图找到一个解决方案,但我不明白为什么会出现这个错误。有可能向我解释我的错误吗?表单直接在api中使用put方法提交。

致以最诚挚的问候,

贝努瓦

1 个答案:

答案 0 :(得分:0)

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

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