I’am writing unit-tests for 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 Doctrine\ORM\EntityManager instance in my unit-tests and pass it to constructor like this:
// 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 make me advise how to improve and automate entity_manager mock creation. I don’t sure that this is the right way to create mocks (creation of this bulky mocks seems inconvenient to me). I will be pleased for any advise.
It sounds like you might be testing a method which starts out by getting a couple of categories, then doing something with them. If that’s the case, could you split the method up?
One method to query the database using $em,
getACoupleOfCategories(), which you can test with a database test if you really want to (though a simple query method shouldn’t need unit testing, as long as you’re comfortable that the query does what it’s meant to)And then another method,
doSomethingWithThem($categories)which in testing you can just pass the categories to directly?Or would that not work for what you’re trying to do?