Symfony2 object manager in tests

I am writing unit tests for a symfony2 project. For example, I want to test some class that requires Doctrine \ ORM \ EntityManger inctance:

// Class for testing // ... class CategoryManager { public function __construct( EntityManager $em ) { // ... 

So, I need to create an instance of Doctrine \ ORM \ EntityManager in my unit tests and pass it to the constructor as follows:

 // Testing // ... $category1 = new Category(); $category2 = new Category(); $categories = array( $category1, $category2 ); $query = $this->getMock( '\Application\BackendBundle\Tests\Mocks\Doctrine\ORM\Query', array(), array(), '', false ); $query->expects( $this->any() ) ->method( 'getResult' ) ->will( $this->returnValue( $categories ) ); $em = $this->getMock( 'Doctrine\ORM\EntityManger', array(), array(), '', false ); $em->expects( $this->any() ) ->method( 'createQuery' ) ->will( $this->returnValue( $query ) ); // ... 

Please help me advise how to improve and automate the creation of entity entities. I'm not sure if this is the right way to create bullying (creating these bulky layouts seems inconvenient to me). I will be happy for any advice.

+4
source share
1 answer

It looks like you can test a method that starts by getting a couple of categories and then doing something with them. If so, could you break up the method?

One method for querying a database with $ em, getACoupleOfCategories() , which you can test with a database test if you really want (although a simple query method does not need unit testing, if it’s convenient for you that the query does what it does meant)

And then another doSomethingWithThem($categories) method, which when testing can simply pass categories directly?

Or will this not work for what you are trying to do?

+1
source

Source: https://habr.com/ru/post/1346517/


All Articles