我在Symfony2上进行了功能测试。它会在测试完成后立即创建一些测试实体,进行测试并删除临时实体。
[CREATE TEMP ENTITIES] => [RUN TESTS] => [DELETE TEMP ENTITIES]
问题是当断言失败时,临时实体不会被删除。
请参阅下面的代码(我评论了未执行的行):
<?php
public function testChangePassword()
{
$enduser = $this->logIn();
$enduserSalt = $enduser->getSalt();
$successMsg = $this->translator->trans('change_pwd.success');
$submitButtonText = $this->translator->trans('change_pwd.submit');
/**
* Test Case 1: Try to change password with incorrect old password
*/
$url = $this->router->generate('userpanel_change_password');
$crawler = $this->client->request('GET', $url);
$form = $crawler->selectButton($submitButtonText)->form(
[
'password_change[old_password]' => 'xaxaxaxa',
'password_change[password][password]' => '123456789',
'password_change[password][confirm]' => '123456789'
]
);
$this->client->followRedirects();
$crawler = $this->client->submit($form);
$this->assertTrue($crawler->filter('html:contains("' . $successMsg . '")')->count() == 2);
/**
* Following line isn't executed when above assertion fails.
*/
$this->removeTestUser();
/**
* Test Case 2: Change password success
*/
$form = $crawler->selectButton($submitButtonText)->form(
[
'password_change[old_password]' => $this->testUserInfo['password'],
'password_change[password][password]' => '123456789',
'password_change[password][confirm]' => '123456789'
]
);
$this->client->followRedirects();
$crawler = $this->client->submit($form);
$this->assertTrue($crawler->filter('html:contains("' . $successMsg . '")')->count() > 0);
$this->removeTestUser();
}
private function logIn()
{
$this->removeTestUser();
$enduser = $this->createTestUser();
$session = $this->client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken($enduser, null, $firewall, array('ROLE_USER'));
$session->set('_security_' . $firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
return $enduser;
}
private function createTestUser($salt = null)
{
$this->removeTestUser();
$newUser = new Enduser();
$newUser->setName($this->testUserInfo['name']);
$newUser->setEmail($this->testUserInfo['email']);
$factory = $this->client->getContainer()->get('security.encoder_factory');
$encoder = $factory->getEncoder($newUser);
$password = $encoder->encodePassword($this->testUserInfo['password'], $newUser->getSalt());
$newUser->setPassword($password);
if (!is_null($salt)) {
$newUser->setSalt($salt);
}
$this->em->persist($newUser);
$this->em->flush();
return $newUser;
}
private function removeTestUser()
{
$this->em->getRepository('LabsCoreBundle:Enduser')->createQueryBuilder('E')
->delete()
->where('E.email = :email')
->setParameter('email', $this->testUserInfo['email'])
->getQuery()
->execute();
}
首先是有一种“总是”在测试后运行的方法,比如symfony1中的postExecute
(可能是关机方法)?
由于我的每个测试都以删除临时实体结束,所以我想在类上实现一个删除这些实体的机制。
我尝试用try / catch块包装断言检查但是没有意义。
答案 0 :(得分:1)
您可以在测试类中使用tearDown()方法,该方法将在每次测试后执行,如果您想在所有测试结束时只运行一次方法,请使用tearDownAfterClass()
的示例