如何测试一个理论库

编辑本页

警告:您正在浏览的文档欧宝官网下载appob娱乐下载Symfony 5.3,现已不再维护。

本页的更新版本用于Syob娱乐下载mfony 6.2(当前稳定版本)。

如何测试一个理论库

另请参阅

主测试指南描述如何为自动化测试使用和设置数据库。本文的内容展示了测试Doctrine存储库的方法。

在单元测试中模拟理论存储库

不建议使用单元测试原则存储库.存储库是针对真实的数据库连接进行测试的。但是,如果您仍然需要这样做,请查看下面的示例。

假设你想要测试的类是这样的:

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/ / src /工资/ SalaryCalculator.php名称空间应用程序工资使用应用程序实体员工使用学说持久性ObjectManagerSalaryCalculator私人objectManager公共函数__construct(ObjectManagerobjectManager->objectManager =objectManager;}公共函数calculateTotalSalaryidemployeeRepository->objectManager->getRepository(员工::类);员工employeeRepository->找到(id);返回员工->getSalary () +员工->getBonus ();}}

EntityManagerInterface通过构造函数注入到类中,您可以在测试中传递一个模拟对象:

12 34 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
/ /测试/工资/ SalaryCalculatorTest.php名称空间应用程序测试工资使用应用程序实体员工使用应用程序工资SalaryCalculator使用学说持久性ObjectManager使用学说持久性ObjectRepository使用PHPUnit)框架TestCaseSalaryCalculatorTest扩展TestCase公共函数testCalculateTotalSalary()员工员工();员工->setSalary (1000);员工->setBonus (1100);//现在,模拟存储库,使其返回员工的模拟employeeRepository->createMock (ObjectRepository::类);//在PHPUnit 5.3或以下使用getMock(// $employeeRepository = $this->getMock(ObjectRepository::class);employeeRepository->预计(->任何())->方法(“发现”->willReturn (员工);//最后,模拟EntityManager以返回存储库的模拟//(如果被测试的类注入//它使用的存储库而不是整个对象管理器)objectManager->createMock (ObjectManager::类);//在PHPUnit 5.3或以下使用getMock(// $this->getMock(objectManager::class);objectManager->预计(->任何())->方法(“getRepository”->willReturn (employeeRepository);salaryCalculatorSalaryCalculator (objectManager);->assertequal (2100salaryCalculator->calculateTotalSalary (1));}}

在本例中,您将由内而外构建模拟,首先创建由对象返回的雇员存储库函数返回EntityManager.这样,测试中就不涉及真正的类。

理论存储库的功能测试

功能测试您将使用实际的Doctrine存储库对数据库进行查询,而不是模仿它们。为此,通过服务容器获取实体管理器,如下所示:

12 34 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
/ /测试/仓库/ ProductRepositoryTest.php名称空间应用程序测试存储库使用应用程序实体产品使用ob娱乐下载FrameworkBundle测试KernelTestCaseProductRepositoryTest扩展KernelTestCase/ * * *@var\学说\ ORM \ EntityManager * /私人entityManager受保护的函数设置()无效内核自我::bootKernel ();->entityManager =内核->getContainer ()->get (“原则”->getManager ();}公共函数testSearchByName()产品->entityManager->getRepository(产品::类)->findOneBy ([“名字”= >“无价的小部件”]);->assertSame (14.50产品->getPrice ());}受保护的函数拆卸()无效::tearDown ();//建议这样做以避免内存泄漏->entityManager->close ();->entityManager =;}}
此工作,包括代码示例,是根据创作共用BY-SA 3.0许可证。
ob娱乐下载Symfony 5.3支持通过JoliCode