Symfony : Mock LDAP in functional tests

I want to do functional tests on my Symfony (5.1) application, this application uses an Active Directory server as a "datas" database (creating , listing , updating datas). I’m using the Symfony ldap component. Code example below may contain typos.

Controller

class DatasController
{
/**
     * @Route("/datas", name="datas")
     * @IsGranted("ROLE_USER")
     *
     * @return Response
     * @desc Displays LDAP datas
     */
    public function datasList(DatasRepository $datasRepository)
    {
        $datas = $datasRepository->findAll();
        return $this->render('datas/list.html.twig', [
            'datas' => $datas,
        ]);
    }
}

Repository

class DatasRepository
{
    private Ldap $ldap;
    private EntryManagerInterface $manager;

    /**
     * DatasRepository constructor.
     * Service injected params
     */
    public function __construct(Ldap $ldap, string $ldapAdminLogin, string $ldapAdminPwd)
    {
        $this->ldap = $ldap->bind($ldapAdminLogin, $ldapAdminPwd);
        $this->manager = $ldap->getEntryManager();
    }
    
    public function create(Data $data): void
    {
        // ... some $data to SymfonyComponentLdapEntry $entry logic
        
        $this->manager->add( $entry );
    }

    /**
     * @return datas[]
     */
    public function findAll()
    {
        $this->ldap->query('ou=test', '(&(objectclass=person))');
        $entries = $query->execute()->toArray();

        // ... some $entries to $datas logic

        return $datas;
    }
    
}

Test

class DatasControllerTest extends WebTestCase
{
    public function testDatasList()
    {
        $client = static::createClient();
        $client->request('GET', '/datas');
        # Crash can't contact LDAP and thats logical
        $this->assertResponseIsSuccessful();
    }
}

So, how to do functional test on "GET /datas" ?
What part of the code should i mock to maximize test efficiency and coverage ?

Some additional information :

  • I can’t have a dedicated LDAP server for tests (tests are run under
    Docker via gitlab-ci)
  • I’m aware of the "don’t mock what you don’t
    own".
  • I’ve read many posts/articles saying "you should mock the
    LdapAdapter" but i have no idea on how to achieve this and haven’t
    found any example.

Any suggestions is welcome.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *