由 phpunit、symfony 测试控制器操作

jag*_*r91 4 php testing phpunit symfony twig

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

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,通常我通过 behat 测试控制器,但这个只是渲染树枝并设置变量,所以我可能无法通过 behat 测试它。我试图通过 phpUnit 测试它并且它可以工作,但是模拟链方法的最佳方法是什么?或者也许你有其他方法来测试它?顺便说一句,容器是私有的,所以我需要反思?你好

Mak*_*hev 6

有两种测试控制器的方法:

  1. 功能测试。您一起测试整个应用程序 - 从从数据库获取数据到在 Symfony 核心中呈现响应。您可以使用夹具来设置测试数据。
  2. 单元测试。您只测试此方法,所有依赖项都被模拟。

单元测试在测试服务方面很好,只有很少的依赖。但对于控制器而言,功能测试在大多数情况下会更好。

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

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..
    }
}
Run Code Online (Sandbox Code Playgroud)