gpt4 book ai didi

unit-testing - 测试中的 Symfony2 实体管理器

转载 作者:行者123 更新时间:2023-12-01 05:41:04 25 4
gpt4 key购买 nike

我正在为 symfony2 项目编写单元测试。例如,我想测试一些需要 Doctrine\ORM\EntityManger 指令的类:

// 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 模拟创建。我不确定这是创建模拟的正确方法(创建这个庞大的模拟对我来说似乎不方便)。我很乐意为您提供任何建议。

最佳答案

听起来您可能正在测试一种方法,该方法从获取几个类别开始,然后对它们进行处理。如果是这样的话,你能把方法分开吗?

一种使用 $em 查询数据库的方法,getACoupleOfCategories() ,您可以使用 database test 进行测试如果你真的想要(虽然一个简单的查询方法不需要单元测试,只要你对查询执行它的意图感到满意)

然后是另一种方法,doSomethingWithThem($categories)在测试中,您可以直接将类别传递给哪个?

或者这对你想要做的事情不起作用?

关于unit-testing - 测试中的 Symfony2 实体管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com