Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3925

How to handle routing with locale in Symfony 4.3 KernelTestCase?

$
0
0

I need to test (PHPUnit) a service in Symfony 4.3 application and that service depends on the framework. It uses Translator and Router and it also depends on User. This means I want to write a KernelTestCase with User (done). The problem is the Router fails because the Routes need _locale. How can I address the issue?

1) App\Tests\blahblah\MenuFactoryTest::testMenuItemsByRoles with data set "ROLE_ADMIN" (array('ROLE_ADMIN'), array(array('Menu Label 1', 'Menu Label 2')))
Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("_locale") to generate a URL for route "default_dashboard".

class MenuFactoryTest extends KernelTestCase
{
    use LogUserTrait; // my trait allowing to emulate a user with particular roles 

    /** @var MenuFactory */
    private $menuFactory;

    protected function setUp(): void
    {
        static::bootKernel();

        $this->menuFactory = static::$container->get(MenuFactory::class);

    }

    // ...

    /**
     * @param array $roles
     * @param array $menuLabels
     *
     * @dataProvider provideMenuItemsByRoles
     */
    public function testMenuItemsByRoles(array $roles, array $menuLabels): void
    {
        $this->logIn($roles);

        $this->assertMenuItemsHaveLabels(
            $menuLabels,
            $this->menuFactory->getMenuItems()
        );
    }

    // ...
}

class MenuFactory implements MenuFactoryInterface
{
    /** @var RouterInterface */
    private $router;

    /** @var AuthorizationCheckerInterface */
    private $securityChecker;

    /** @var TranslatorInterface */
    private $translator;

    public function __construct(
        RouterInterface $router,
        AuthorizationCheckerInterface $securityChecker,
        TranslatorInterface $translator
    ) {
        $this->router = $router;
        $this->securityChecker = $securityChecker;
        $this->translator = $translator;
    }

    public function getMenuItems(string $appMenuName = null): array
    {
        $menuItems = [];

        $dashboardMenu = new DefaultMenuItem(
            $this->translator->trans('menu.dashboard'),
            $this->router->generate('default_dashboard'),
            'fa fa-dashboard'
        );

        $menuItems[] = $dashboardMenu;

        // ...

        return $menuItems;
    }
}


Viewing all articles
Browse latest Browse all 3925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>