首页 > 解决方案 > 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 还是获取真实数据值?我有点卡在这里。

谢谢你。

标签: symfonytestingphpunit

解决方案


好的,所以 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);
}

希望这可以帮助


推荐阅读