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