phpunit Functional Tests Failed getRepository - php

I'm running phpunit test but, I can't use getRepository to get $amount from my databases.
I don't know how to fix it.
I get this
1) Tests\BankBundle\Controller\BankControllerTest::testMoneyIn
Failed asserting that null matches expected 50
<?php
namespace Tests\BankBundle\Controller;
use BankBundle\Entity\entry;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class BankControllerTest extends WebTestCase
{
/**
* #var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* {#inheritDoc}
*/
public function setUp(): void
{
self::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager();
}
public function testMoneyIn()
{
$client = static::createClient();
$client->request('POST', '/bank/moneyin', array('amount' => 50));
$query = $this->em
->getRepository('BankBundle:entry')
->getAmount();
$this->assertEquals(50, $query);
}

Related

Call to a member function has() on null

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
}
}

Problems with Unit test on symfony

)
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.

ObjectManager The method createQuery() does not seem to exist

I have class like this which works and returns feedbacks from the database
namespace Acme\Bundle\AcmeBundle\Handler;
use Doctrine\Common\Persistence\ManagerRegistry;
class FeedbackHandler implements FeedbackHandlerInterface
{
private $em;
private $entityClass;
private $repository;
public function __construct(ManagerRegistry $mr, $entityClass)
{
$this->em = $mr->getManager();
$this->entityClass = $entityClass;
$this->repository = $this->em->getRepository($this->entityClass);
}
public function get($id)
{
return $this->repository->find($id);
}
public function all($limit = 50, $offset = 0)
{
$feedbacks = $this->em->createQuery("SELECT f FROM AcmeAcmeBundle:Feedback f")
->setFirstResult($offset)
->setMaxResults($limit)
->getResult();
return array( "feedback" => $feedbacks );
}
}
however when I submit code to scrutinizer-ci.com it reports that
The method createQuery() does not seem to exist on
object
same with PhpStorm, it displays warning at this line. Is there an approach to fix this issue?
Add a #var phpdoc comment for the $em variable ...
... or (even better) #return to ManagerRegistry's getManager() method.
Then PHPStorm / scrutinizer-ci will both know of which type $em is and that it has a createQuery() method.
This is a good practice in general and will enable autocompletion in PHPStorm, too.
example:
/** #var \Doctrine\ORM\EntityManager */
private $em;
... or ...
class ManagerRegistry
{
/**
* ...
*
* #return \Doctrine\ORM\EntityManager
*/
public function getManager()
{
// ...

test a repository in symfony

I have the following method in my repository and I want to test it
public function myFindOne($id)
{
// On passe par le QueryBuilder vide de l'EntityManager pour l'exemple
$qb = $this->_em->createQueryBuilder();
$qb->select('a')
->from('xxxBundle:entity', 'a')
->where('a.id = :id')
->setParameter('id', $id);
return $qb->getQuery()
->getResult();}
I found the following code in the documentation, but I could not understand it
// src/Acme/StoreBundle/Tests/Entity/ProductRepositoryFunctionalTest.php
namespace Acme\StoreBundle\Tests\Entity;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ProductRepositoryFunctionalTest extends WebTestCase
{
/**
* #var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* {#inheritDoc}
*/
public function setUp()
{
static::$kernel = static::createKernel();
static::$kernel->boot();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
}
public function testSearchByCategoryName()
{
$products = $this->em
->getRepository('AcmeStoreBundle:Product')
->searchByCategoryName('foo')
;
$this->assertCount(1, $products);
}
/**
* {#inheritDoc}
*/
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
}
To see what you should edit in this code, the testSearchByCatergory() should be a good start. In this example, it gets the result of the tested method into $products and checks that this collection contains only one element.
So I guess your test would be to test that the returned object is the one you expect to be returned. But heh, like #cheesemacfly said, your repo is kinda the same as findOne[ById]()... Oh and BTW, you should check up phpunit [EN] (Or in FR, as I saw in your comment) documentation to see how you should make it run.
Cheers. :)
From Symfony's official documentation, the Repository methods should be tested as follow:
// tests/AppBundle/Entity/ProductRepositoryTest.php
namespace Tests\AppBundle\Entity;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class ProductRepositoryTest extends KernelTestCase
{
/**
* #var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* {#inheritDoc}
*/
protected function setUp()
{
self::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager();
}
public function testSearchByCategoryName()
{
$products = $this->em
->getRepository('AppBundle:Product')
->searchByCategoryName('foo')
;
$this->assertCount(1, $products);
}
/**
* {#inheritDoc}
*/
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
}

accessing entity manager inside phpunittest

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;

Categories