gpt4 book ai didi

php - 通过 phpunit、symfony 测试 Controller Action

转载 作者:行者123 更新时间:2023-11-28 20:04:33 26 4
gpt4 key购买 nike

我需要测试我的 Controller Action 并且需要建议。这是我的 Controller 的样子:

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 测试 Controller ,但这个只是渲染 Twig 并设置变量,所以我可能无法通过 behat 测试它。我试图通过 phpUnit 对其进行测试并且它可以工作,但是模拟链方法的最佳方法是什么?或者也许您有其他方法可以测试它?顺便说一句,容器是私有(private)的,所以我需要反射?问候

最佳答案

有两种测试 Controller 的方法:

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

单元测试非常适合测试只有很少依赖项的服务。但对于 Controller Functional tests在大多数情况下更好。

功能测试与 session 模拟在你的情况下可能看起来像:

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

关于php - 通过 phpunit、symfony 测试 Controller Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47308481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com