php - 如何在 Symfony 功能测试中模拟?
问题描述
我正在 Symfony 3.4 应用程序上创建功能测试。
<?php
namespace AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
class UserControllerTest extends WebTestCase
{
/**
* Connect to the website while being logged in
* Logs in with (admin, password : a)
*/
public function connection()
{
$client = static::createClient();
$container = static::$kernel->getContainer();
$session = $container->get('session');
// Get the user (has to exist in the database)
$person = self::$kernel->getContainer()->get('doctrine')->getRepository('AppBundle:User')->findOneByUsername('admin');
$token = new UsernamePasswordToken($person, null, 'main', $person->getRoles());
$session->set('_security_main', serialize($token));
$session->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
// Return the client
return $client;
}
public function accessEditPage()
{
$client = $this->connection();
$crawler = $client->request('GET', '/user/');
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
$this->assertContains(
'Liste des utilisateurices',
$client->getResponse()->getContent()
);
// Select the button of the user created for the test
// Wont work if there are already more than 10 users in the database
$link = $crawler
->filter('tr > td > a:contains("")')
->last()
->link()
;
$crawler = $client->click($link);
return array($client,$crawler);
}
/**
* Create a new user
*/
public function testCreate()
{
$client = $this->connection();
$crawler = $client->request('GET', '/user/new');
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
// Vérifie si la page affiche le bon texte
$this->assertContains(
'Enregistrer',
$client->getResponse()->getContent()
);
// Select the form and fill its values
$form = $crawler->selectButton(' Créer')->form();
$values = $form->getPhpValues();
$values['appbundle_user']['username'] = 'Jean';
$values['appbundle_user']['plainPassword']['first'] = 'motdepasse';
$values['appbundle_user']['plainPassword']['second'] = 'motdepasse';
$crawler = $client->request($form->getMethod(), $form->getUri(), $values,$form->getPhpFiles());
$crawler = $client->followRedirect();
$this->assertContains(
'Jean',
$client->getResponse()->getContent()
);
}
}
目前,我的控制器测试创建数据库条目并依赖于现有的条目,这是一个问题。
我想模拟控制器中使用的存储库,以避免在测试控制器时创建条目,但我还没有找到有用的文档。由于我找不到文档,我也想知道我想做的是否是一个好的做法。
解决方案
推荐阅读
- reactjs - React Native Image 无法解析模块
- facebook - Facebook Live 视频突然停止工作,连 Facebook 团队都批准了权限?
- mongodb - Grails 3.1 - 域实例的空属性保存在 mongodb
- javascript - 点击时的Javascript文本循环
- word2vec - word2vec 中的词汇大小与向量大小
- python - 使用while循环检查文件中是否存在字符串
- javascript - 使用 chrome 扩展覆盖用户定义的函数以使用本机函数
- java - 使用springboot连接多个Kafka服务器
- javascript - 如何用 JavaScript 或 jQuery 中的值替换整个输入字段?
- vue.js - 与 Browserify 的单个文件组件分开包含 Vue 运行时