我想在PHPUnit中为我的symfony 2项目准备简单的函数测试:验证用户并显示一些页面而不重定向到登录表单。 我使用LDAP用户提供程序(IMAG \ LdapBundle \ Provider \ LdapUserProvider)。 我在security.yml中的防火墙配置:
firewalls:
secured_area:
pattern: ^/
provider: ldap
imag_ldap:
login_path: /login
logout:
path: /logout
target: /
在我的测试控制器中,我有以下方法:
protected function createClientWithAuthentication($firewallName, array $options = array(), array $server = array())
{
$client = $this->createClient($options, $server);
$client->getCookieJar()->set(new \Symfony\Component\BrowserKit\Cookie(session_name(), true));
$user = $this->getCurrentUser($client);
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$client->getContainer()->get('session')->set('_security_' . $firewallName, serialize($token));
return $client;
}
protected function getCurrentUser($client) {
$userProvider = $client->getContainer()->get('imag_ldap.security.user.provider');
$user = $userProvider->loadUserByUsername('my.login');
return $user;
}
然后我进行了简单的测试:
public function testProfile()
{
$c = $this->createClientWithAuthentication('secured_area');
$c->request('GET', '/profile');
$this->assertEquals($c->getResponse()->getStatusCode(), 200);
}
测试失败:
无法断言200场比赛预期为302。
我挖了它,我发现我收到了来自用户提供商的完整用户(所有字段都已正确填写)。但响应正在重定向到localhost / login页面。
请告诉我还有什么可以测试......如果应该(或不是)显示登录页面,决定的地方在哪里?
答案 0 :(得分:1)
我有WebTestCase基类,可以创建授权客户端。你可以根据自己的目的进行调整......
class BaseWebTestCase extends WebTestCase{
protected $client;
protected function setUp(){
$this->client=$this->createAuthorizedClient();
}
/**
* @return \Symfony\Bundle\FrameworkBundle\Client
*/
protected function createAuthorizedClient()
{
$client = static::createClient();
$container = $client->getContainer();
/** @var Person $user */
$user=$container->get("netnotes.cust.person")->getRepository()->getSuperAdmin();
$session = $container->get('session');
/** @var $userManager \FOS\UserBundle\Doctrine\UserManager */
$userManager = $container->get('fos_user.user_manager');
/** @var $loginManager \FOS\UserBundle\Security\LoginManager */
$loginManager = $container->get('fos_user.security.login_manager');
$firewallName = $container->getParameter('fos_user.firewall_name');
$user = $userManager->findUserBy(array('username' => $user->getUsername()));
$loginManager->loginUser($firewallName, $user);
// save the login token into the session and put it in a cookie
$container->get('session')->set('_security_' . $firewallName,
serialize($container->get('security.context')->getToken()));
$container->get('session')->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
return $client;
}
}