0
我想写一些Symfony2功能测试,使用PHPUnit,模拟登录用户通过AJAX调用请求一些资源。Symfony2功能测试会话和帖子
该测试首先模拟用户使用标准FOSUserBundle登录表单登录;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
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('[email protected]', '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和4.5.0的PHPUnit
谢谢 - 正如你可以想象的,我试图改变各种参数来回应其他论坛上的建议。按照您的建议设置storage_id引发了一个不同的错误,但我通过在phpunit的配置文件中将“process isolation”设置为false来修复该错误。测试现在运行。谢谢。 – 2015-03-19 09:23:07
@AndrewBattye很高兴帮助:) – 2015-03-19 09:28:32
经过更多的实验,我放弃了这个测试。上面提出的方法确实可以正确设置会话,但是在阅读Symfony文档后,我发现测试中使用的容器与正在测试的代码使用的容器不同 - 因此测试中的会话是不同的会话可以被测试中的控制器访问。我会尝试使用Behat进行测试! – 2015-03-20 10:09:15