phpUnit测试存储库Symfony findOneBy

时间:2018-12-16 20:29:01

标签: symfony testing phpunit

我很熟悉Symfony 3中的phpunit,我想知道在测试存储库时应该遵循什么。例如,我具有以下回购功能:

/**
 * {@inheritdoc}
 */
public function findAdminRole()
{
    $role = $this->repository->findOneBy(['name' => Role::ADMIN]);

    if (null === $role) {
        throw new NotFoundException();
    }

    return $role;
}

对此进行的确切测试是什么样的?我应该测试函数findOneBy和NotFoundException是否被调用还是要获取真实的数据值?我有点卡在这里。

谢谢。

1 个答案:

答案 0 :(得分:0)

好的,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
)

现在我们有一个仓库的模拟,让我们看看样本测试的样子

第一次测试

   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);
    }

用与上面相同的方式,您可以编写另一个测试,例如: 第二次测试

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);
}

希望这会有所帮助