感谢你来到这里
                我真的很激动
                盼望,能有你的支持
            捐赠可扫描二维码转账支付
                
                    支付宝扫一扫付款
                    微信扫一扫付款
(微信为保护隐私,不显示你的昵称)
在Symfony项目中进行Doctrine repository的单元测试是不推荐的。当你正处理repository时,你是在真正应对一些“针对真实数据库连接”的测试。
幸运的是,你可以很容易对真实数据库进行测试,如下所述。
当你要执行真实查询时,你需要启动kernel来获取有效(db)连接。本例中,你要继承 KernelTestCase,它会令所有这些变得极其简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  | // tests/AppBundle/Repository/ProductRepositoryTest.php
namespace Tests\AppBundle\Repository;
 
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
 
class ProductRepositoryTest extends KernelTestCase
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;
 
    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        self::bootKernel();
 
        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }
 
    public function testSearchByCategoryName()
    {
        $products = $this->em
            ->getRepository('AppBundle:Product')
            ->searchByCategoryName('foo')
        ;
 
        $this->assertCount(1, $products);
    }
 
    /**
     * {@inheritDoc}
     */
    protected function tearDown()
    {
        parent::tearDown();
 
        $this->em->close();
        $this->em = null; // avoid memory leaks / 避免内存泄露
    }
} | 
本文,包括例程代码在内,采用的是 Creative Commons BY-SA 3.0 创作共用授权。