)
Since 2 days I do unit tests on queries and I have some problems, here is the code and the tests:
request:
<?php
namespace CampaignBundle\Service;
use Doctrine\ORM\EntityManager;
use AccessBundle\Model\UserInterface;
use AccessBundle\Service\CountryFilter;
class CampaignProvider
{
/** #var EntityManager */
protected $em;
/** #var CountryFilter */
protected $countryFiler;
/**
* CampaignProvider constructor.
* #param EntityManager $entityManager
* #param CountryFilter $countryFilter
*/
public function __construct(EntityManager $entityManager, CountryFilter $countryFilter)
{
$this->em = $entityManager;
$this->countryFiler = $countryFilter;
}
/**
* #return \Doctrine\ORM\EntityRepository|CampaignBundle\Entity\CampaignRepository
*/
protected function getRepository()
{
return $this->em->getRepository('CampaignBundle:Campaign');
}
/**
* #return array
* #throws \Exception
*/
public function getCampaign()
{
$queryBuilder = $this->getCampaignQb();
return $queryBuilder->getQuery()->getResult();
}
/**
* #return \Doctrine\ORM\QueryBuilder
* #throws \Exception
*/
public function getCampaignQb()
{
$repository = $this->getRepository();
$queryBuilder = $repository->createQueryBuilder('c');
$queryBuilder
->where('c.isDeleted = 0')
->addOrderBy('c.id', 'DESC');
return $queryBuilder;
}
}
Test:
<?php
/**
* Created by PhpStorm.
* User: mickael
* Date: 24/12/18
* Time: 14:10
*/
namespace CampaignBundle\Tests\Service;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use AccessBundle\Service\CountryFilter;
use CampaignBundle\Entity\Campaign;
use CampaignBundle\Service\CampaignProvider;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class CampaignProviderTest extends KernelTestCase
{
/** #var EntityManager */
private $entityManager;
/** #var CampaignProvider */
private $campaignProvider;
/** #var CountryFilter */
private $countryFilter;
/** #var TokenStorageInterface */
private $tokenStorage;
/** #var AuthorizationCheckerInterface */
private $authorizationChecker;
public function setUp()
{
$this->entityManager = $this->getMockBuilder('\Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$this->tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')
->disableOriginalConstructor()
->getMock();
$this->authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')
->disableOriginalConstructor()
->getMock();
$this->countryFilter = new CountryFilter($this->tokenStorage, $this->authorizationChecker, $this->entityManager);
$this->campaignProvider = new CampaignProvider($this->entityManager, $this->countryFilter);
}
public function testGetCampaign()
{
$queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setMethods(array('getQuery', 'getCampaignQb'))
->disableOriginalConstructor()
->getMock();
$queryBuilder->expects($this->once())
->method('getCampaignQb')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->once())
->method('getQuery')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->once())
->method('getResult')
->will($this->returnValue($queryBuilder));
$this->campaignProvider->getCampaign();
}
public function testGetCampaignQb()
{
$repository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')
->disableOriginalConstructor()
->setMethods(array('createQueryBuilder'))
->getMock();
$queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setMethods(array('where', 'addOrderBy', 'createQueryBuilder'))
->disableOriginalConstructor()
->getMock();
$repository->expects($this->once())
->method('createQueryBuilder')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->once())
->method('where')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->once())
->method('addOrderBy')
->will($this->returnValue($queryBuilder));
$entityManager = $this->getMockBuilder('\Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$entityManager->expects($this->once())
->method('getRepository')
->will($this->returnValue($repository));
$this->campaignProvider->getCampaignQb();
}
}
When I run the tests I get:
PHP Fatal error: Call to a member function createQueryBuilder() on null in
I admit that I have some problems when it comes to testing the queries, can you help me please?
Thank you ;)
edit :
edit my all post
ps: CountryFilter its a service i call in CampaignProvider
You're mocking the entity manager, but you're not passing it to the CampaignProvider in your tests: $this->campaignProvider doesn't know about the local $entityManager variable.
You need to either put it in the constructor call if you're using constructor injection or in a setEntityManager method if you're using method injection.
Related
im learning symfony. I have a twig using twig extension and i found that i cannot call a function from other controller inside twig extension.
so i have decide to use a service since the twig extension is using the service.
so i tried to call a function from controller in the service and call the function from the service in the twig extension.
Then, i have an error message that [Call to a member function has() on null], where $doct = $this->getDoctrine()->getManager(); in the controller.
this is the function in the controller that i'm trying to use
edited
namespace Customize\Controller;
use Customize\Entity\CustomRing;
use Customize\Entity\Ring;
use Customize\Repository\CustomProductRepository;
use Eccube\Controller\AbstractController;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Product;
use Eccube\Entity\ProductClass;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\ProductClassRepository;
use Eccube\Service\CartService;
use Eccube\Service\OrderHelper;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Eccube\Service\PurchaseFlow\PurchaseFlowResult;
use Google\Service\Monitoring\Custom;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class CartController extends AbstractController
{
/**
* #var ProductClassRepository
*/
protected $productClassRepository;
/**
* #var CartService
*/
protected $cartService;
/**
* #var PurchaseFlow
*/
protected $purchaseFlow;
/**
* #var BaseInfo
*/
protected $baseInfo;
/**
* #var CustomProductRepository
*/
protected $customProductRepository;
/**
* CartController constructor.
*
* #param ProductClassRepository $productClassRepository
* #param CartService $cartService
* #param PurchaseFlow $cartPurchaseFlow
* #param BaseInfoRepository $baseInfoRepository
* #param CustomProductRepository $customProductRepository
*/
public function __construct(
ProductClassRepository $productClassRepository,
CartService $cartService,
PurchaseFlow $cartPurchaseFlow,
BaseInfoRepository $baseInfoRepository,
CustomProductRepository $customProductRepository
) {
$this->productClassRepository = $productClassRepository;
$this->cartService = $cartService;
$this->purchaseFlow = $cartPurchaseFlow;
$this->baseInfo = $baseInfoRepository->get();
$this->customProductRepository = $customProductRepository;
}
public function image_route(){
$Carts = $this->cartService->getCarts();
$doct = $this->getDoctrine()->getManager();
$custom_images = array();
$Custom_product = $this->customProductRepository->customProductFindByName();
$Product = $doct->getRepository(Product::class)->find($Custom_product[0]->getId());
foreach ($Carts as $Cart) {
$items = $Cart->getCartItems();
foreach($items as $item ){
if($item->getProductClass()->getProduct()->getId() == $Product->getId()){
$custom = $item->getProductClass()->getCode();
$custom = $doct->getRepository(CustomRing::class)->find($custom);
$ring = $doct->getRepository(Ring::class)->find($custom->getRingBaseId());
$upload_directory= $this->getParameter('uploads_directory');
$ring_shape = $ring->getRingShape();
$ring_type = $ring->getRingType();
$upload = $upload_directory.'/customRing/ring/'.$ring_shape.'/'.$ring_type.'/';
$images = glob($upload."*.{jpg,png,jpeg,JPG,JPEG,PNG}", GLOB_BRACE);
for($i=0;$i<count($images);$i++){
$aa = explode('save_image/', $images[$i]);
$images[$i] = $aa[1];
}
array_push($custom_images,$images[0]);
}
}
}
return $custom_images;
use Customize\Controller\CartController;
/**
* #var CartController
*/
protected $cartController;
public function __construct(
SessionInterface $session,
EntityManagerInterface $entityManager,
ProductClassRepository $productClassRepository,
CartRepository $cartRepository,
CartItemComparator $cartItemComparator,
CartItemAllocator $cartItemAllocator,
OrderRepository $orderRepository,
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $authorizationChecker,
CartController $CartController
) {
$this->session = $session;
$this->entityManager = $entityManager;
$this->productClassRepository = $productClassRepository;
$this->cartRepository = $cartRepository;
$this->cartItemComparator = $cartItemComparator;
$this->cartItemAllocator = $cartItemAllocator;
$this->orderRepository = $orderRepository;
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
$this->cartController = $CartController;
}
/*other functions
.
.
*/
public function imagess(){
$temp = $this->cartController->image_route();
return $temp;
}
and this is the twig extension
use Eccube\Service\CartService;
class CartServiceExtension extends AbstractExtension
{
/**
* #var CartService
*/
protected $cartService;
public function get_image_route(){
$t = $this->cartService->imagess();
return $t;
//return ['11', '12'];
}
}
The line i got error in controller is
$doct = $this->getDoctrine()->getManager();
and when go inside getDoctrine()
trait ControllerTrait{
/**
* Shortcut to return the Doctrine Registry service.
*
* #return ManagerRegistry
*
* #throws \LogicException If DoctrineBundle is not available
*
* #final
*/
protected function getDoctrine()
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
}
return $this->container->get('doctrine');
}
I don't know why but it seems has() function inside getDoctrine() returns null
how can i use the function from the controller so that i can pass the values of $custom_images into the twig?
To get Doctrine in any controller action, you can do away with that function/trait entirely and just inject the EntityManagerInterface into your action.
For example:
class SomeCustomController extends AbstractController
{
public function someControllerAction(Request $request, EntityManagerInterface $em): Response
{
// business logic
}
}
I'm tracing a weird error in a Symfony 2 app and I'd like to know if there's a way to print log messages from a Repository PHP file. For example:
class OrderEntityRepository extends EntityRepository
{
/**
*
* #param mixed $filter
* #return type
*/
public function findByCriteria($filter) {
[...]
/* I'D LIKE TO LOG SOME VARIABLES FROM HERE */
}
}
I've tried using error_log() but nothing happens.
Is this possible? Thanks in advance,
It's possible but it's usually not a good practice. The good thing to do is to send back the Repository result to your Controller or Service and you log from them an error or something else.
But if you still want to do it, Repository are like services (when you implements ServiceEntityRepository see this slide for more information). If you want to log something specific inside you have to inject the LoggerInterface into your Repository configuration (like you do with service).
In your service.yml (or xml) if you don't use autowire:
Your\Repository:
arguments: ['#logger']
In your repository class:
/**
* #var LoggerInterface
*/
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
On symfony 3.8 I have
class BlahRepository extends ServiceEntityRepository
{
/* #var ContainerInterface $container */
private $container;
/* #var LoggerInterface $logger */
private $logger;
public function __construct(RegistryInterface $registry, ContainerInterface $container, LoggerInterface $logger)
{
parent::__construct($registry, Blah::class);
$this->container = $container;
$this->logger = $logger;
}
}
and I am able to use $this->logger->info("text")
I think the trick may be extending ServiceEntityRepository
In order to use dependency injection for Doctrine entity repositories, you can create a custom RepositoryFactory.
Tested on Symfony 3.4.
<?php
namespace AppBundle\Doctrine;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
use Doctrine\ORM\Repository\RepositoryFactory as RepositoryFactoryInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
class RepositoryFactory implements RepositoryFactoryInterface, LoggerAwareInterface
{
/** #var DefaultRepositoryFactory */
protected $defaultRepositoryFactory;
/** #var LoggerInterface */
private $logger;
/**
* #required (for autowiring)
* #param LoggerInterface $logger (Monolog will be the default one)
*/
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
/**
* #see Configuration::getRepositoryFactory()
*/
public function __construct()
{
$this->defaultRepositoryFactory = new DefaultRepositoryFactory();
}
/**
* Gets the repository for an entity class.
*
* #param EntityManagerInterface $entityManager
* #param string $entityName The name of the entity.
* #return ObjectRepository
*/
public function getRepository(EntityManagerInterface $entityManager, $entityName): ObjectRepository
{
$repository = $this->defaultRepositoryFactory->getRepository($entityManager, $entityName);
if ($repository instanceof LoggerAwareInterface && $this->logger !== null) {
$repository->setLogger($this->logger);
}
return $repository;
}
}
Declare it in Doctrine configuration.
# app/config.yml
doctrine:
# ...
orm:
repository_factory: AppBundle\Doctrine\RepositoryFactory
And finally, make your repository class implement LoggerAwareInterface.
class OrderEntityRepository extends EntityRepository implements LoggerAwareInterface
{
/** #var LoggerInterface */
private $logger;
/**
* #param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
/**
* #param mixed $filter
* #return type
*/
public function findByCriteria($filter) {
//[...]
$this->logger->alert('message');
}
}
You can also make a LoggerAwareTrait trait to spare yourself some code duplication.
I'm writting some tests for a web application, and one of them is Failing when in production & development is working fine.
That's the fail:
myMelomanBundle\Publication\CreatePublicationUseCaseTest::shouldCreateAPublicationOneTimeIfItDoesNotExist
TypeError: Argument 1 passed to myDomain\Entity\Publication::setUser() must be an instance of myDomain\Entity\User, null given, called in /var/www/melomaniacs/src/myDomain/UseCases/Publication/CreatePublicationUseCase.php on line 48
CreatePublicationUseCaseTest.php:
<?php
namespace myMelomanBundle\Publication;
use myDomain\Entity\Publication;
use myDomain\UseCases\Publication\CreatePublicationUseCase;
use myMelomanBundle\Repository\UserRepository;
use myMelomanBundle\Repository\PublicationRepository;
use PHPUnit_Framework_MockObject_MockObject;
use Doctrine\ORM\EntityManagerInterface;
use myDomain\Entity\User;
class CreatePublicationUseCaseTest extends \PHPUnit_Framework_TestCase
{
const USER_ID = 2;
const MESSAGE = "message";
const URI = "spotify:uri:47n4in3482nk";
/**
* #var CreatePublicationUseCase
*/
private $createPublicationUseCase;
/**
* #var PHPUnit_Framework_MockObject_MockObject
*/
private $userRepositoryMock;
/**
* #var PHPUnit_Framework_MockObject_MockObject
*/
private $publicationRepositoryMock;
/**
* #var PHPUnit_Framework_MockObject_MockObject
*/
private $aDispatcherMock;
/**
* #var PHPUnit_Framework_MockObject_MockObject
*/
private $aEntityMock;
/**
* #var PHPUnit_Framework_MockObject_MockObject
*/
private $userMock;
protected function setUp()
{
$this->userRepositoryMock = $this->createMock(UserRepository::class);
$this->publicationRepositoryMock = $this->createMock(PublicationRepository::class);
$this->aEntityMock = $this->createMock(EntityManagerInterface::class);
$this->createPublicationUseCase = new CreatePublicationUseCase($this->publicationRepositoryMock, $this->userRepositoryMock, $this->aEntityMock);
$this->userMock = $this->createMock(User::class);
}
protected function tearDown()
{
$this->userRepositoryMock = null;
$this->publicationRepositoryMock = null;
$this->createPublicationUseCase = null;
$this->userMock = null;
}
/** #test */
public function dummyTest()
{
$this->createPublicationUseCase;
}
/** #test */
public function shouldCreateAPublicationOneTimeIfItDoesNotExist()
{
$this->givenAPublicationRepositoryThatDoesNotHaveASpecificPublication();
$this->thenThePublicationShouldBeSavedOnce();
$this->whenTheCreateUserUseCaseIsExecutedWithASpecificParameters();
}
private function givenAPublicationRepositoryThatDoesNotHaveASpecificPublication()
{
$this->publicationRepositoryMock
->method('find')
->willReturn(false);
}
private function thenThePublicationShouldBeSavedOnce()
{
$this->publicationRepositoryMock
->expects($this->once())
->method('create')
->willReturn($this->isInstanceOf(Publication::class));
}
private function whenTheCreateUserUseCaseIsExecutedWithASpecificParameters()
{
$this->createPublicationUseCase->execute(self::USER_ID, self::MESSAGE, null);
}
}
CreatePublicationUseCase.php
<?php
namespace myDomain\UseCases\Publication;
use Doctrine\ORM\EntityManagerInterface;
use myDomain\Entity\Publication;
use myDomain\Entity\User;
use myDomain\PublicationRepositoryInterface;
use myDomain\UserRepositoryInterface;
use myMelomanBundle\Repository\PublicationRepository;
use myMelomanBundle\Repository\UserRepository;
class CreatePublicationUseCase
{
/**
* #var PublicationRepository
*/
private $publicationRepository;
/**
* #var UserRepository
*/
private $userRepository;
private $entityManager;
public function __construct(
PublicationRepositoryInterface $publicationRepository,
UserRepositoryInterface $userRepository,
EntityManagerInterface $entityManager
)
{
$this->publicationRepository = $publicationRepository;
$this->userRepository = $userRepository;
$this->entityManager = $entityManager;
}
public function execute($userId, $message = null, $uri = null)
{
try{
/**
* #var User $user
*/
$user = $this->userRepository->findOneBy(array('id'=>$userId));
\Doctrine\Common\Util\Debug::dump($user);die; => Here
$publication = new Publication();
$publication->setMessage($message == null ? '' : $message);
$publication->setCreatedAt(new \DateTime());
$publication->setUser($user);
$publication->setStatus(0);
$publication->setLink($uri == null ? '' : $uri);
$this->publicationRepository->create($publication);
$this->entityManager->flush();
return $publication;
} catch (\Exception $e) {
return false;
}
}
}
Note that where is the dump , it returns the user object properly, just on the Test it's returning NULL.
On the test, it should be getting to me same User object result that without the test, shouldn't be?
What I'm doing wrong?
It looks like your issue is coming from the following line from CreatePublicationUseCase::execute
$user = $this->userRepository->findOneBy(array('id'=>$userId));
In your test, you pass in a mocked UserRepository but you don't mock the output of findOneBy.
$this->userRepositoryMock = $this->createMock(UserRepository::class);
I believe you will have the results you want if you also mock the results with something like the following.
$this->userRepositoryMock
->expects($this->once())
->method('findOneBy')
->will($this->returnValue(<value>));
I have a symfony application where I am attempting to update an entity in the database using a setter. However when I update the entity and call $this->em->flush() the entity is not persisted to the database.
Here is my service:
<?php
namespace AppBundle\Service;
use AppBundle\Exceptions\UserNotFoundException;
use Doctrine\ORM\EntityManager;
use AppBundle\Entity\User;
/**
* Class MyService
* #package AppBundle\Service
*/
class MyService extends BaseService {
/**
* #var EntityManager
*/
protected $em;
/**
* #var User
*/
protected $user;
/**
* MyService constructor.
* #param EntityManager $em
*/
public function __construct(EntityManager $em){
$this->em = $em;
}
/**
* See if a user email exists
* #param string $email
* #return bool
*/
public function checkEmailExists($email){
$this->user = $this->em
->getRepository('AppBundle:User')
->findOneBy(['email' => $email]);
return !(is_null($this->user));
}
/**
* add credit to a users account
* #param User $user
* #param integer $credit
*/
public function addCredit(User $user, $credit){
$user->addCredit($credit);
$this->em->flush();
}
/**
* add a credit to a users account
* #param $email
* #param $credit
*/
public function addCreditByEmail($email, $credit){
if(!($this->checkEmailExists($email))){
throw new UserNotFoundException(sprintf('User with email %s not found.', $email));
}
$this->addCredit($this->user, $credit);
}
}
Here is my test:
<?php
namespace AppBundle\Tests\Service;
use AppBundle\DataFixtures\ORM\PurchaseFixture;
use AppBundle\Entity\Vendor;
use AppBundle\Repository\OfferRepository;
use AppBundle\Tests\TestCase;
use AppBundle\Entity\Offer;
use AppBundle\DataFixtures\ORM\OfferFixture;
use AppBundle\DataFixtures\ORM\PaymentSystemFixture;
/**
* Class UserOfferServiceTest
* #package AppBundle\Tests\Service
*/
class MyServiceTest extends TestCase implements ServiceTestInterface
{
function __construct($name = null, array $data = [], $dataName = '')
{
$this->setFixtures([
'AppBundle\DataFixtures\ORM\CityFixture',
'AppBundle\DataFixtures\ORM\CountryFixture',
'AppBundle\DataFixtures\ORM\PaymentSystemFixture',
'AppBundle\DAtaFixtures\ORM\UserFixture',
]);
parent::__construct($name, $data, $dataName);
}
/**
* test the checkEmailExists() of app.vendor
*/
public function testCheckEmailExists(){
$myService = $this->getService();
$this->assertTrue($myService->checkEmailExists('user1#user1.com'));
$this->assertFalse($myService->checkEmailExists($this->fake()->safeEmail));
}
/**
* test the addCredit functionality
*/
public function testAddCredit(){
$myService = $this->getService();
$user = $this->getUser();
$this->assertEquals(0, $user->getCredit());
$toAdd = $this->fake()->numberBetween(1, 500);
$myService->addCredit($user, $toAdd);
$this->assertEquals($toAdd, $user->getCredit());
}
/**
* test the addCreditByEmail functionality
*/
public function testAddCreditByEmail(){
$myService = $this->getService();
$user = $this->getUser();
$email = $this->getUser()->getEmail();
$this->assertEquals(0, $user->getCredit());
$toAdd = $this->fake()->numberBetween(1, 500);
$myService->addCreditByEmail($email, $toAdd);
$updatedUser = $this->getEntityManager()
->getRepository('AppBundle:User')
->findOneBy(['email' => $email]);
$this->assertEquals($toAdd, $updatedUser->getCredit());
}
/**
* #return \AppBundle\Service\VendorService|object
*/
public function getService(){
$this->seedDatabase();
$this->client = $this->createClient();
return $this->client->getContainer()->get('app.admin_kiosk');
}
}
The testAddCredit() test passes (because I'm checking the same object), but the testAddCreditByEmail fails with the following error: 1) AppBundle\Tests\Service\MyServiceTest::testAddCreditByEmail
Failed asserting that null matches expected 149.
I've tried persisting the entity, flushing the entity (like: $this->em->flush($user)) all to no avail. Please let me know how I can fix this.
I found the issue.
In the test case I just had to refresh the entity by doing $this->getEntityManager()->refresh($user) (on the original $user entity). Thanks!
I have the following unit test code in symfony:
<?php
// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace Shopious\MainBundle\Tests;
class ShippingCostTest extends \PHPUnit_Framework_TestCase
{
public function testShippingCost()
{
$em = $this->kernel->getContainer()->get('doctrine.orm.entity_manager');
$query = $em->createQueryBuilder();
$query->select('c')
->from("ShopiousUserBundle:City", 'c');
$result = $query->getQuery()->getResult();
var_dump($result);
}
}
and I am trying to access the entity manager here, howver it always gives me this error:
Undefined property: Acme\MainBundle\Tests\ShippingCostTest::$kernel
To achieve this you need to create a base test class (let's call it KernelAwareTest) with following contents:
<?php
namespace Shopious\MainBundle\Tests;
require_once dirname(__DIR__).'/../../../app/AppKernel.php';
/**
* Test case class helpful with Entity tests requiring the database interaction.
* For regular entity tests it's better to extend standard \PHPUnit_Framework_TestCase instead.
*/
abstract class KernelAwareTest extends \PHPUnit_Framework_TestCase
{
/**
* #var \Symfony\Component\HttpKernel\Kernel
*/
protected $kernel;
/**
* #var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* #var \Symfony\Component\DependencyInjection\Container
*/
protected $container;
/**
* #return null
*/
public function setUp()
{
$this->kernel = new \AppKernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
$this->entityManager = $this->container->get('doctrine')->getManager();
$this->generateSchema();
parent::setUp();
}
/**
* #return null
*/
public function tearDown()
{
$this->kernel->shutdown();
parent::tearDown();
}
/**
* #return null
*/
protected function generateSchema()
{
$metadatas = $this->getMetadatas();
if (!empty($metadatas)) {
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
$tool->dropSchema($metadatas);
$tool->createSchema($metadatas);
}
}
/**
* #return array
*/
protected function getMetadatas()
{
return $this->entityManager->getMetadataFactory()->getAllMetadata();
}
}
Then your own test class will be extended from this one:
<?php
namespace Shopious\MainBundle\Tests;
use Shopious\MainBundle\Tests\KernelAwareTest;
class ShippingCostTest extends KernelAwareTest
{
public function setUp()
{
parent::setUp();
// Your own setUp() goes here
}
// Tests themselves
}
And then use parent's class methods. In your case, to access entity manager, do:
$entityManager = $this->entityManager;