symfony2 如何测试与数据库交互的代码

来源:互联网 发布:淘宝粉星便利店靠谱么 编辑:程序博客网 时间:2024/05/01 08:55

1.如果您的代码与数据库进行交互,例如读取数据或存储数据到它,您需要调整您的测试,以考虑这一考虑。有很多方法可以解决这个问题。在一个单元测试中,您可以创建一个模拟库,并使用它来返回预期的对象。在功能测试中,您可能需要使用预定义的值来准备一个测试数据库,以确保您的测试始终具有相同的数据来工作。

2.在单元测试中模拟存储库

3.如果你想测试代码,这取决于一个独立的原则,你需要模拟存储库。通常你注入EntityManager进入你的类,用它来存储库。这使事情变得更加困难,你需要模拟的EntityManager和你的库类。

4.通过注册您的存储库作为工厂服务,它可以直接注入您的存储库。这是一个小的工作来设置,但使测试更容易,因为你只需要模拟存储库。

5/假设你要测试的类看起来像这样:

namespace AppBundle\Salary;

use Doctrine\Common\Persistence\ObjectManager;

class SalaryCalculator

{

    private $entityManager;


    public function __construct(ObjectManager $entityManager)

    {

        $this->entityManager = $entityManager;

    }

     public function calculateTotalSalary($id)

    {

        $employeeRepository = $this->entityManager

            ->getRepository('AppBundle:Employee');

        $employee = $employeeRepository->find($id);


        return $employee->getSalary() + $employee->getBonus();

    }

}

由于本能通过构造函数注入类,在测试通过模拟对象很容易:

use AppBundle\Salary\SalaryCalculator;


class SalaryCalculatorTest extends \PHPUnit_Framework_TestCase

{

    public function testCalculateTotalSalary()

    {

        // First, mock the object to be used in the test

        $employee = $this->getMock('\AppBundle\Entity\Employee');

        $employee->expects($this->once())

            ->method('getSalary')

            ->will($this->returnValue(1000));

        $employee->expects($this->once())

            ->method('getBonus')

            ->will($this->returnValue(1100));


        // Now, mock the repository so it returns the mock of the employee

        $employeeRepository = $this

            ->getMockBuilder('\Doctrine\ORM\EntityRepository')

            ->disableOriginalConstructor()

            ->getMock();

        $employeeRepository->expects($this->once())

            ->method('find')

            ->will($this->returnValue($employee));


        // Last, mock the EntityManager to return the mock of the repository

        $entityManager = $this

            ->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')

            ->disableOriginalConstructor()

            ->getMock();

        $entityManager->expects($this->once())

            ->method('getRepository')

            ->will($this->returnValue($employeeRepository));


        $salaryCalculator = new SalaryCalculator($entityManager);

        $this->assertEquals(2100, $salaryCalculator->calculateTotalSalary(1));

    }

}

在这个例子中,你由内而外的建筑模型,首先创建并通过库返回的员工,其本身被EntityManager返回。这种方式,没有真正的类参与测试。

二、如果你有功能测试,你希望他们与一个真实的数据库进行交互。大多数的时候,你要使用专用的数据库连接,以确保不改写你输入的数据时,你输入的应用程序,也可以清除数据库之前,每一个测试。

要做到这一点,你可以指定一个数据库配置,覆盖默认的配置:

# app/config/config_test.yml

doctrine:

    # ...

    dbal:

        host:     localhost

        dbname:   testdb

        user:     testdb

        password: testdb

0 0
原创粉丝点击