我需要测试我的控制器动作,我需要建议。 这就是我的控制器的外观:
class SampleController extends Controller
{
public function sampleAction(Request $request)
{
$lang = 'en';
return $this->render('movie.html.twig', [
'icons' => $this->container->getParameter('icons'),
'language' => $lang,
'extraServiceUrl' => $this->getAccount()->getExtraServiceUrl(),
'websiteUrl' => $this->getAccount()->getWebsiteUrl(),
'myProfileUrl' => $this->getAccount()->getMyProfileUrl(),
'redirectForAnonUser' => $this->container->get('router')->generate('login'),
'containerId' => $request->getSession()->get("_website"),
'isRestricted' => $this->getLicense()->isRestricted(),
'isPremiumAvaible' => $this->getLicense()->isPremiumAvaible()
]);
}
private function getAccount()
{
return $this->container->get('context')->getAccount();
}
private function getLicense()
{
return $this->container->get('license');
}
}
现在,通常我用behat测试控制器,但是这个只是渲染树枝并设置变量,所以我可能无法用behat测试它。我尝试通过phpUnit测试它,它可以工作,但是模拟链方法的最佳方法是什么?或者你可能有其他方法来测试它? btw容器是私有的,所以我需要反思? 问候
答案 0 :(得分:4)
有两种测试控制器的方法:
单元测试很好地测试服务,只有很少的依赖。但对于控制器Functional tests在大多数情况下更好。
在您的情况下,功能测试会话模拟可能如下所示:
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PostControllerTest extends WebTestCase
{
public function testYourAction()
{
$client = static::createClient();
$user = null;//todo: load user for test from DB here
/** @var Session $session */
$session = $client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$session->set('_security_'.$firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
$crawler = $client->request('GET', '/your_url');
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode());
//todo: do other assertions. For example, check that some string is present in response, etc..
}
}