Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Example below tests repository and entity manager actions.


Class


namespace Application\FrontendBundle\Service;

use Application\FrontendBundle\Entity\Country;
use Application\FrontendBundle\Exception\CountryException;
use Application\FrontendBundle\Repository\CountryRepository;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use Exception;
use Symfony\Component\Form\Form;

class CountryService implements CountryServiceInterface
{
private $entityManager;
private $countryRepository;

public function __construct(
EntityManager $entityManager,
CountryRepository $countryRepository
) {
$this->entityManager = $entityManager;
$this->countryRepository = $countryRepository;
}

public function delete($id)
{
$country = $this->countryRepository->findOneById($id);
if (! $country instanceof Country) {
throw new CountryException(
sprintf('Country [%s] cannot be found.', $id)
);
}

try {
$this->entityManager->remove($country);
$this->entityManager->flush();

return true;
} catch (DBALException $e) {
$message = sprintf('DBALException: %s', $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException: %s', $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception: %s', $e->getMessage());
}

throw new CountryException($message);
}
}

Test


namespace spec\Application\FrontendBundle\Service;

use Application\FrontendBundle\Entity\Country;
use Application\FrontendBundle\Exception\CountryException;
use Application\FrontendBundle\Repository\CountryRepository;
use Doctrine\ORM\EntityManager;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CountryServiceSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Application\FrontendBundle\Service\CountryService');
}

function let(
EntityManager $entityManager,
CountryRepository $countryRepository
) {
$this->beConstructedWith(
$entityManager,
$countryRepository
);
}

function it_should_throw_exception_for_non_existing_country(
CountryRepository $countryRepository
) {
$id = 99;
$countryRepository->findOneById($id)->willReturn(null);

$this->shouldThrow(
new CountryException(
sprintf('Country [%s] cannot be found.', $id)
)
)->during('delete', [$id]);
}

function it_should_remove_country(
EntityManager $entityManager,
CountryRepository $countryRepository,
Country $country
) {
$id = 99;
$countryRepository->findOneById($id)->willReturn($country);
$entityManager->remove($country)->shouldBeCalled();
$entityManager->flush()->shouldBeCalled();

$this->delete($id)->shouldReturn(true);
}
}