我们如何模拟一个Symfony rest api控制器,其参数中带有一个Repository本身在其构造函数中具有ManagerRegistry

时间:2018-10-06 13:46:42

标签: rest api symfony testing mocking

我正在尝试在symfony 3.4中对我的API控制器进行功能测试,但是由于存在这样的后遗症,我遇到了问题。

class AdminRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Admin::class);
    }
}

事实上,由于进行了这些更改,因此我决定像这样将回购注入到我的控制器中。

public function getMyReservationAction(Request $request, AdminRepository $adminRepos, ReservationRepository $reservationRepos)
{
    $values = json_decode($request->getContent(), true);

    return $this->verifValid(
            Header::getToken($request)
            , $values['reservation_id']
            , $adminRepos
            , $reservationRepos
    );
}

问题是我通过使用$ adminRepos的verifValid方法传递AdminRepository来调用数据库。 而且我想测试我的控制器,所以决定像这样模拟存储库。

public function testGetMyReservationAction() {

    $token = $this->createUser(true,'ROLE_USER');


    $admin = new Admin();
    $admin->setEmail('test@test.com');

    // Now, mock the repository so it returns the mock of the admin
    $adminRepos = $this->getMockBuilder(AdminRepository::class)
        ->disableOriginalConstructor()
        ->getMock();
    $adminRepos->expects($this->any())
        ->method('findBy')
        ->willReturn(Array($admin));

    $entityManager = $this
        ->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')
        ->disableOriginalConstructor()
        ->setMethods(['getRepository', 'clear'])
        ->getMock();

    $entityManager
        ->expects($this->once())
        ->method('getRepository')
        ->with(Admin::class)
        ->will($this->returnValue($adminRepos));

    $this->client->getContainer()->set('doctrine.orm.default_entity_manager', $entityManager);

    // Set the client
    $this->client->getContainer()->set('doctrine', $entityManager);

    //Initialisation des paramètres
    $params = [
        'token' => $token
        , 'reservation_id' => $this->getReservation()->getId()
    ];


    //On appelle la route
    $this->client->request('POST', '/auth/reservation/getone'
        , array() , array()
        , array('HTTP_AUTHORIZATION' => 'Bearer '. $token)
        , json_encode($params)
    );

    //On vérifie que le code de retour est bien 200
    $this->assertEquals(200 , $this->client->getResponse()->getStatusCode());
}

但它告诉我我必须实例化我的ManagerRegistry。

  PHP Fatal error:  Class Mock_ManagerRegistry_90efed4b contains 11 abstract methods and must therefore be declared abstract or implement the remaining
 methods (Doctrine\Common\Persistence\ManagerRegistry::getDefaultManagerName, Doctrine\Common\Persistence\ManagerRegistry::getManager, Doctrine\Common
\Persistence\ManagerRegistry::getManagers, ...) in phar:///usr/local
/bin/phpunit/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 1

我不认为必须这样做,所以我认为我做错了事,但我不知道在哪里。

你能帮我吗? 预先谢谢你。

0 个答案:

没有答案