由phpunit、symfony测试控制器动作

由phpunit、symfony测试控制器动作,php,symfony,testing,twig,phpunit,Php,Symfony,Testing,Twig,Phpunit,我需要测试我的控制器动作,我需要建议。 这就是我的控制器的外观: class SampleController extends Controller { public function sampleAction(Request $request) { $lang = 'en'; return $this->render('movie.html.twig', [ 'icons' => $this->

我需要测试我的控制器动作,我需要建议。 这就是我的控制器的外观:

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测试它,它可以工作,但是模拟链方法的最佳方法是什么?或者你有其他方法来测试它? 顺便说一句,容器是私有的,所以我需要反射?
问候语

测试控制器有两种方法:

  • 功能测试。您可以一起测试整个应用程序—从db获取数据到在Symfony core中呈现响应。您可以使用设置测试数据
  • 单元测试。如果只测试此方法,则会模拟所有依赖项
  • 单元测试在测试依赖关系很少的服务时很好。但在大多数情况下,控制器的性能更好

    功能测试带有会话模拟在您的情况下,可以如下所示:

    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..
        }
    }
    

    通常,您会对这类事情使用功能(也称为集成)测试。问题是,即使你模拟了所有的东西,并设法让一个像样的单元测试工作起来,它也将是非常脆弱的,因为最小的html更改都会导致它失败。