symfony - PhpUnit 测试存储库 Symfony findOneBy
问题描述
我对 Symfony 3 中的 phpunit 很熟悉,我想知道在测试存储库时应该遵循什么。例如,我有以下回购功能:
/**
* {@inheritdoc}
*/
public function findAdminRole()
{
$role = $this->repository->findOneBy(['name' => Role::ADMIN]);
if (null === $role) {
throw new NotFoundException();
}
return $role;
}
对此的测试究竟是什么样的?我应该测试调用函数 findOneBy 和 NotFoundException 还是获取真实数据值?我有点卡在这里。
谢谢你。
解决方案
好的,所以 findOneBY 返回 Null 或 Object,您可以设置将返回 Null 或说角色对象的示例数据并对其进行测试,我认为这可以帮助您入门。所以,在设置中我会模拟存储库:
$this->mockRepository = $this
->getMockBuilder('path to the respository')
->disableOriginalConstructor()
->setMethods(array('if you want to stub any'))
->getMock();
$this->object = new class( //this is the class under test
// all your other mocked services, ex : logger or anything else
)
现在我们有一个 repo 的模拟,让我们看看示例测试的样子
第一次测试
public function findAdminRoleTestReturnsException(){
$name = ['name' => Role::ABC]; // consider this will return Null result from DB due to whatever reason
$exception = new NotFoundException();
// do whatever other assertions you need here
$this->mockRepository->expects($this->any())
->method('findOneBY')
->with($name)
->will($this->returnValue(null));
// Now call the function
$role = $this->object->findAdminRole();
$this->assertEquals($exception, $role);
}
以与上述相同的方式,您可以编写另一个测试,例如: 2nd test
public function findAdminRoleTestReturnsNewRole(){
$name = ['name' => Role::ADMIN] // this will find the entry in theDB
$ testRoleObject = new Role();
$this->mockRepository->expects($this->any())
->method('findOneBY')
->with($name)
->will($this->returnValue($testRoleObject));
// Now call the function
$role = $this->object->findAdminRole();
$this->assertEquals($testRoleObject, $role);
}
希望这可以帮助
推荐阅读
- python - 如何拆分括号内用逗号分隔的字符串
- reactjs - react-stripe-elements v1.1.0 createPaymentMethod 在 react 15.6.2 中不起作用
- facebook-graph-api - Facebook Graph API - 无权发布到群组
- google-analytics - Shopify - 如何在页面加载后加载谷歌分析?
- javascript - 离线创建反应应用程序需要什么?
- node.js - Firebase 未更新到节点 12
- angular - Angular10 中的延迟加载路由
- sql - 如何从下面的 SQL 表中获取结果查询?
- docker - 在 linux 上使用 docker 安装商店软件,并在 503 上出错
- ios - UI 没有填满整个屏幕。顶部和底部的黑条