测试中的 Symfony2 实体管理器
我正在为 symfony2 项目编写单元测试。例如,我想测试一些需要 Doctrine\ORM\EntityManger inctance 的类:
// Class for testing
// ...
class CategoryManager
{
public function __construct( EntityManager $em )
{
// ...
因此,我需要在单元测试中创建 Doctrine\ORM\EntityManager 实例并将其传递给构造函数,如下所示:
// 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 ) );
// ...
请让我建议如何改进和自动创建entity_manager模拟。我不确定这是创建模拟的正确方法(创建这个庞大的模拟对我来说似乎不方便)。我将很高兴提供任何建议。
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.
听起来您可能正在测试一种方法,该方法首先获取几个类别,然后对它们执行某些操作。如果是这样的话,你能把这个方法分开吗?
使用 $em 查询数据库的一种方法是
getACoupleOfCategories()
,您可以使用 数据库测试 如果你真的想要的话(尽管简单的查询方法不需要单元测试,只要你对查询执行其应有的功能感到满意)然后是另一种方法,
doSomethingWithThem($categories)
在测试中您可以直接将类别传递给哪个?或者这对你想做的事情不起作用?
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?