我正在尝试使用PHPUnit编写一些Symfony2功能测试,模拟登录用户通过AJAX调用请求某些资源。
该测试首先使用标准的FOSUserBundle登录表单模拟用户登录;
use SymfonyBundleFrameworkBundleTestWebTestCase;
class MyWebTestCase extends WebTestCase {
public function login($username, $password = 'password')
{
$client = static::createClient();
$client->followRedirects(true);
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('Login')->form(array(
'_username' => $username,
'_password' => $password,
));
$crawler = $client->submit($form);
return $client;
}
}
然后,测试从数据库中获取一个实体,并将其设置在会话变量中,然后发送POST请求以检索所请求的资源,使用一些JSON,其中包括关于所请求内容的额外信息(在实际应用程序中,一些JavaScript根据用户的操作编写JSON,然后通过AJAX提交);
$this->client = $this->login('user@domain.com', 'password');
// we want element number 6 from the fixtures
$chart = $this->em->getRepository('MyBundle:Element')->find(6);
$guid = $chart->getGuid();
$this->client->getContainer()->get('session')->set($guid, $chart);
$link = sprintf('/viewer/data/%d/%s', 1, $guid);
$crawler = $this->client->request('POST', $link, array(), array(),
array('CONTENT_TYPE' => 'application/json'),
'{"filters":[]}');
当测试达到这一点时,就会产生一个错误;
ini_set(): A session is active. You cannot change the session module's ini settings at this time
我使用的是Symfony 2.6.5和PHPUnit 4.5.0
您的测试使用模拟会话吗?如果不试试这个。
配置测试yml
framework:
test: ~
session:
storage_id: session.storage.mock_file
本机会话存储旨在处理每个进程的单个请求,这可能会导致您的错误。如果是你的情况。