[英]phpunit + Symfony2: There is no message specifying which tests are failing
[英]PHPUnit failing with Symfony2 Sessions
嘗試在實現Sessions的控制器方法上運行基於控制器的單元測試時,我遇到了一個問題。
在這種情況下,這是控制器方法:
/**
* @Route("/api/logout")
*/
public function logoutAction()
{
$session = new Session();
$session->clear();
return $this->render('PassportApiBundle:Login:logout.html.twig');
}
功能測試:
public function testLogout()
{
$client = static::createClient();
$crawler = $client->request('GET', '/api/logout');
$this->assertTrue($client->getResponse()->isSuccessful());
}
產生的錯誤:
無法啟動會話,因為已經發送了標頭。 (500內部服務器錯誤)
我試過放入$this->app['session.test'] = true;
進入測試,但仍然沒有去。 有沒有人嘗試解決這樣的問題來對使用會話的控制器進行單元測試?
首先,您應該使用容器中的會話對象。 所以你的行動看起來應該更像:
/**
* @Route("/api/logout")
*/
public function logoutAction()
{
$session = $this->get('session');
$session->clear();
return $this->render('PassportApiBundle:Login:logout.html.twig');
}
然后在您的測試中,您可以將服務注入“客戶端容器”。 所以:
public function testLogout()
{
$sessionMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session')
->setMethods(array('clear'))
->disableOriginalConstructor()
->getMock();
// example assertion:
$sessionMock->expects($this->once())
->method('clear');
$client = static::createClient();
$container = $client->getContainer();
$container->set('session', $sessionMock);
$crawler = $client->request('GET', '/api/logout');
$this->assertTrue($client->getResponse()->isSuccessful());
}
使用此代碼,您可以使用會話服務完成所需的一切。 但你必須要注意兩件事:
編輯:
我添加了一個斷言
在我的情況下,它足以設置
framework:
session:
storage_id: session.storage.mock_file
在config_test.yml
。 YMMV,我沒有那么多想法,我實際上在做什么,但它對我有用。
這里只是為了完成塞浦路斯的回應。
正如Sven解釋並在查看symfony的文檔http://symfony.com/doc/2.3/components/http_foundation/session_testing.html時 ,您必須使用MockFileSessionStorage對象將模擬會話實例化為第一個構造函數參數。
你需要使用:
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
代碼應該是:
$sessionMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')
->setMethods(array('clear'))
->disableOriginalConstructor()
->setConstructorArgs(array(new MockFileSessionStorage()))
->getMock();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.