Getting a mock Doctrine\ORM\QueryBuilder - php

I've been trying all day to write some tests for a class that parses a custom DSL and creates DQL queries.
My class requires that I pass in a queryBuilder which it then uses to build the query and return it.
The problem I have is that
to get a queryBuilder I need an entityManager
to get an entityManager I need a connection
to get a connection I need a database
I'd rather that my unit tests didn't rely on a database so I've been trying to create a mock queryBuilder using PHPUnit but queryBuilder seems to rely on the entityManager which in turn relies on a connection.
So 2 questions:
Is there a better way to dynamically construct queries in Doctrine 2?
Is there a way to get a working queryBuilder without an entityManager (or at least without a real database)?

I'm not sure how to do it with PHPUnit, but I would recommend checking out Mockery for your PHP mocking needs. It's a really powerful library which allows you to mock the EntityManager pretty easily, and therefore anything that it will return.
For your use case, you can easily create a Mock entity manager than will return you a mock query builder:
$mockEm = \Mockery::mock('\Doctrine\ORM\EntityManager');
$mockQb = \Mockery::mock('\Doctrine\ORM\QueryBuilder');
$mockEm->shouldReceive('createQueryBuilder')->andReturn($mockQb);
Then you can use Mockery's core functionality to set the expectations you require for your unit test.
On a slight aside, you also get the option of using a 'passive' EntityManager mock, in case you want to unit test a function which contains some database logic, but you don't actually want to go to the database in your unit test.
public function getPassiveEntityManagerMock() {
return \Mockery::mock('\Doctrine\ORM\EntityManager',
array('getRepository' => new FakeRepository(),
'getClassMetadata' => (object)array('name' => 'aClass'),
'persist' => null,
'flush' => null));
}
Here's a suggested way of doing it with PHPUnit, but I haven't tried it out myself.

I ended up creating my own mock query builder; it may have been possible to get the same functionality using PHPUnits mocking framework but this is wha I ended up with:
<?php
namespace MyNameSpace\Tests\Mocks;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Common\Collections\ArrayCollection;
class MockQueryBuilder extends QueryBuilder {
protected $expr;
protected $paramReflect;
public function __construct($expr) {
$this->expr = $expr;
$this->paramReflect = new \ReflectionProperty('Doctrine\ORM\QueryBuilder', 'parameters');
$this->paramReflect->setAccessible(true);
$this->paramReflect->setValue($this, new ArrayCollection());
}
/*
* #return Query\Expr
*/
public function expr() {
return $this->expr;
}
public function getEntityManager() {
return null;
}
public function getQuery() {
return array(
'parameters' => clone $this->paramReflect->getValue($this),
'dql' => $this->getDQL(),
);
}
}

Related

How to use symfony, twig, and doctrine in a controller inside an existing project

I have been using the SymfonyCast on Symfony 4 to try and help me to connect the pieces. I have learned a lot about doctrine Symfony and twig and the environment that they are supposed to work together in. However, that is not what I have to build on. I need to build inside an existing project OpenEMR.
I posted my project code here:
https://github.com/juggernautsei/symfony_twig_doctrine_component/blob/master/library/financialreports/src/FinancialSummaryByInsuranceController.php
The controller works to load the twig template. Now, I am trying to populate the controller with data from the database. I have built the entity class and the repository class. I just can't figure out what to put in this line.
public function getpaidata($insurerid)
{
$payments = $this->repository
}
To access the class in the repository. The IDE suggested the code in the repository class.
public function getInsurerPaid(ArSession $insurerId)
{
/*$insurerPaid = $this->_em->getRepository($this->_entityName)->findBy([
"payer_id" => $insurerId
]);*/
$insurerPaid = $this->findBy([
'payer_id' => $insurerId
]);
return $insurerPaid;
}
But as I am typing in out the code in the controller, the IDE PHPStorm is not suggesting anything. So, I am stuck. I have tried the suggested code here
https://symfony.com/doc/2.0/book/doctrine.html#creating-an-entity-class
https://symfonycasts.com/screencast/symfony-doctrine/repository
but nothing tells me how to access the method that is in the repository class.
UPDATE:
The getpaiddata() method is now changed to
/**
* #return Fully hydrated object.
*/
public function getpaidata($insurerid)
{
$row = $this->repository->findBy([
"payer_id" => $insurerid
]);
return $row;
}
The problem is likely how you get $this->repository. If you fetch it via the entity manager, via $this->_em->getRepository($entityName) like in the commented snippet, the return value has a type hint which tells the IDE that it is just a generic EntityRepository instead of your custom repository class.
You can install the Symfony-plugin to PhpStorm, which will give you better autocompletion if your entity has the right annotation #Entity(repositoryClass="...").
In a typical Symfony 4 application you could also just inject the correct repository, instead of the EntityManager, e.g. in your constructor:
public function __construct(PaidDataRepository $repository)
{
$this->repository = $repository;
}
From what it looks like, OpenEMR has it's own way of creating the EntityManager using Connector::instance(). So this will probably not work for you easily, unfortunately.
Another way around this would be to just place a type hint above assigning your variable:
/** #var App\Repository\PaidDataRepository $repository */
$repository = $this->_em->getRepository(PaidData::class)
or, since you have a class variable you can put a similar annotation on there.

How to use additionProvider with repository functions?

I am trying to configure test classes for my Symfony 2.7 project. I am testing a controller that uses doctrine for connecting to the data base.
I finally managed to do it extending KernelTestCase in order to avoid this Fatal error: Call to a member function "X" on a non-object. But here is the problem: I was triying to order my code and simplify 5 test functions into one by using a additionProvider:
public function additionProvider()
{
$first=$this->service->getTranslation("","en");
return array
(
'original not created' =>array($first,"")
);
}
and I want to use it like:
/**
* #dataProvider additionProvider
*/
public function testGetTranslation($expected, $actual)
{
$this->assertEquals($expected, $actual);
}
here is my setUp():
public function setUp()
{
self::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
$this->service = new \DictionaryBundle\Controller\UtilController($this->em);
}
I tried to add the first test like this and the error appeared again, like if it couldn't access to the repository. So, is possible to use addittionProviders with repository functions? how?
Thanks!
The dataProvider is executed before the setup method. So the service variable is not yet initialized.
So the dataprovider method can only return data, you need to move the call to the service in the tested method.
Here the paragraph of the doc:
Note All data providers are executed before both the call to the
setUpBeforeClass static method and the first call to the setUp method.
Because of that you can't access any variables you create there from
within a data provider. This is required in order for PHPUnit to be
able to compute the total number of tests.

How to access get method in a Test Class Symfony2

I have to write a test class to test my service methods. In my controllers I could access the service by doing $service = $this->get('myService'); and I could access my methods by doing $service->someMethod();.
Now I want to write a test class to test some of the service methods, I tried doing like the doc :
class ServiceTest extends \PHPUnit_Framework_TestCase {
public function testSomeMethod() {
$service = $this->get('myService');
....
}
}
When I launch the test I get something like : Fatal error : Call to undefined method XXX\XXXBundle\Tests\Services\ServicesTest::get() in ...
So my question is how can I use get method to be able to call my service methods
You don't need to use the container in order to test services and other classes.
You should create a new instance of the class and inject the dependencies using test doubles.
Test doubles
- since you don't want to write a functional testing and to use the real dependencies you should be using a test double.
for example if one of the service dependencies is the EntityManager what would happen is that a new entries would be inserted into the Database (or deleted from it) and its not the purpose of Unit testing (you do need to check this tho if you are writing a functional test).
And that's how you should approach this kind of testings:
public function testSomeServiceAdd()
{
$dependencyOne = $this->getMockBuilder('Acme\SomeBundle\DependencyOne')->
disableOriginalConstructor()->
getMock();
$dependencyTwo = $this->getMockBuilder('Acme\SomeBundle\DependencyTwo')->
disableOriginalConstructor()->
getMock();
$service = new SomeService($dependencyOne, $dependencyTwo);
$response = $service->add(1, 2);
$this->assertEquals($response, 3);
}
As you can see I am "mocking" the dependencies and injecting it into the service, after that i'm calling the method and asserting the result.
I would also like to suggest a Mocking framework instead of using the built-in PHPUnit mocking functions. it's easier to use and it has much more mocking functionality:
https://github.com/danrevah/ShortifyPunit
To test your services you should extend the KernelTestCase class.
class ServiceTest extends KernelTestCase
{
private $service;
/**
* {#inheritDoc}
*/
public function setUp()
{
self::bootKernel();
$this->service = static::$kernel->getContainer()
->get('my_service')
;
}
}

Laravel extend Eloquent and 3rd party class

I'm currently working on my first PHP/Laravel 4 project, I'm developing on it a storage class to add Eloquent support to a 3rd party library.
My EloquentStorage class extends the AbstractStorage class from the library, and I make usage of most of AbstractStorage methods. Now that I want to add Eloquent support to my new EloquentStorage class, I faced the fact that PHP does not support multiple inheritance.
Is there a proper way to define an Eloquent model without extending it as:
class MyClass extends Eloquent {}
And, if not, how to deal with such situation when I need to extend 3rd party class and also extend Eloquent? Maybe using Laravel's IoC?
I think your model should extend from Eloquent, and instead be accessed through a repository. Your repository can have a $storage property, and would be responsible for calling the appropriate methods on your AbstractStorage implementation. Below is more pseudo- than actual code, but illustrates where you can plug in your implementation for an update operation.
class MyClass extends Eloquent
{
/* Normal Eloquent model implementation */
}
class MyRepository
{
protected $storage;
protected $myClass;
public function __construct(MyClass $myClass, AbstractStorage $storage)
{
$this->myClass = $myClass;
$this->storage = $storage;
}
public function update($id, $data)
{
// This is just an example operation, basically here's your chance to call
// the 3rd-party implementation. Here is pre-eloquent update, but can be
// after
$this->storage->update($id, $data);
// Use the empty Eloquent class property instance to obtain an instance of
// the requested model
$instance = $this->myClass->find($id);
// set instance properties
$instance->save();
// Example post-eloquent update
$this->storage->update($id, $data);
}
}
class MyStorage extends AbstractStorage { /* Your Storage Implementation */ }
$repo = new MyRepository(new MyClass, new MyStorage);
// Update item id 42's foo property
$repo->update(42, [ 'foo' => 'bar' ]);
A benefit to this approach is that the construction of the repository itself can be offloaded to the IoC through a Service Provider, and be injected inside of a controller / form validator etc, which means the execution will become automatic and hide the underlying complexity of the 3rd party library from the rest of the system (the repository helps keep your 3rd party abstraction from leaking).
Another benefit is that you don't need any special code in your eloquent models having anything to do with your completely unrelated 3rd party code. All of the logic is encapsulated in a single spot, and can even be shared amongst multiple models. Want to change 3rd party providers? Write a new implementation of AbstractStorage, update the service provider and you're done.
One other benefit is improved testability. Instead of statically utilizing an eloquent model directly (a la $user = User::find($id)) you would be manipulating your repository object instead ($user = $this->repo->find($id)). Since your repository can be trivially mocked and itself be tested (without also testing Eloquent or hitting the database), you can write integration tests on all of your controller routes and know the moment that changes to your codebase break your business rules.

Using Doctrine inside ZF2 Models

I'm working for the first time to get Doctrine working with a new ZF2 app. Doctrine is working fine if I call it within the controller (like every last tutorial out there has you do), however it doesn't make any sense performing business logic in the controller.
A few things I found suggests dependency injection passing the Entity Manager in from the controller, some suggest having your class implement ServiceLocatorAwareInterface.
My question is, how is anyone else using it within their models? Surely someone is using it the correct (MVC) way and not putting all of their business logic within their application controllers?
There are of course different solutions for this, but I personally use a Service layer. So for instance you would have a UserService which takes care of handling the business logic of User objects.
To allow the service to do its job you would inject its dependencies. Implementing ServiceLocatorAwareInterface is an option, but if you find yourself using getServiceLocator()->get('...') a lot it becomes a pita to write unit tests and injecting mock objects. A hybrid solution for that would be to have your service implement ServiceLocatorAwareInterface and have a getServiceA() and setServiceA() method where the getServiceA would look like:
if (!$this->serviceA)
{
$this->getServiceLocator()->get('ServiceA');
}
return $this->serviceA;
That way you can still inject a mock version of the dependency in your unit test.
I usually make a Service and instantiate it with a Factory in which I inject either the ServiceLocator or the EntityManager itself directly into the service. The typical folder structure would look something like
\src
\Module
\Controller
\Service
BusinessService.php
\Factory
BusinessServiceFactory.php
In your Module.php or the equivalent in module.config.php for that matter
function getServiceConfig() {
return array(
'factories' => array(
'service.business' => 'Module\src\Module\Factory\BusinessServiceFactory,
),
)
}
Then the actual Service and the Factory itself
BusinessServiceFactory.php
namespace Module\Factory\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class BusinessServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$service = new BusinessService($serviceLocator);
return $service;
}
}
BusinessService.php
namespace Module\Service;
use Zend\ServiceManager\ServiceLocatorInterface;
class BusinessService
{
/**
* #var Service locator
*/
protected $serviceLocator;
public function __construct(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
}
You can now define all your business logic in the BusinessService class. It is callable from your Controllers by this->serviceLocator->get('service.business')

Categories