with example

$listener, , $httpUtils$options] = $this->getListener($dispatcher);

        $logoutEventDispatched = false;
        $dispatcher->addListener(LogoutEvent::classfunction D) use (&$logoutEventDispatched) {
            $logoutEventDispatched = true;
        });

        $request = new Request();

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request$options['logout_path'])
            ->willReturn(false);

        $listener(new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST));

        $this->assertFalse($logoutEventDispatched, 'LogoutEvent should not have been dispatched.');
    }

    public function testHandleMatchedPathWithCsrfValidation()
    {
        $tokenManager = $this->getTokenManager();
        $dispatcher = $this->getEventDispatcher();

        [
use Symfony\Component\Form\Guess\ValueGuess;

class DoctrineOrmTypeGuesserTest extends TestCase
{
    /** * @dataProvider requiredType */
    public function testTypeGuesser(string $type$expected)
    {
        $classMetadata = $this->createMock(ClassMetadata::class);
        $classMetadata->fieldMappings['field'] = true;
        $classMetadata->expects($this->once())->method('getTypeOfField')->with('field')->willReturn($type);

        $this->assertEquals($expected$this->getGuesser($classMetadata)->guessType('TestEntity', 'field'));
    }

    public static function requiredType()
    {
        yield [Types::DATE_IMMUTABLE, new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE)];
        yield [Types::DATE_MUTABLE, new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', [], Guess::HIGH_CONFIDENCE)];

        yield [Types::TIME_IMMUTABLE, new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE)];
        yield [Types::TIME_MUTABLE, new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', [], Guess::HIGH_CONFIDENCE)];

        
use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;

class RedisSenderTest extends TestCase
{
    public function testSend()
    {
        $envelope = new Envelope(new DummyMessage('Oy'));
        $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]];

        $connection = $this->createMock(Connection::class);
        $connection->expects($this->once())->method('add')->with($encoded['body']$encoded['headers'])->willReturn('THE_MESSAGE_ID');

        $serializer = $this->createMock(SerializerInterface::class);
        $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded);

        $sender = new RedisSender($connection$serializer);

        /** @var TransportMessageIdStamp $stamp */
        $stamp = $sender->send($envelope)->last(TransportMessageIdStamp::class);

        $this->assertNotNull($stampsprintf('A "%s" stamp should be added', TransportMessageIdStamp::class));
        $this->assertSame('THE_MESSAGE_ID', $stamp->getId());
    }
->willReturn($plugin);
    $this->assertSame($plugin$this->searchPluginCollection->get('banana'));
  }

  /** * Tests the get() method with a configurable plugin. */
  public function testGetWithConfigurablePlugin() {
    $plugin = $this->createMock('Drupal\search\Plugin\ConfigurableSearchPluginInterface');
    $plugin->expects($this->once())
      ->method('setSearchPageId')
      ->with('fruit_stand')
      ->willReturn($plugin);

    $this->pluginManager->expects($this->once())
      ->method('createInstance')
      ->willReturn($plugin);

    $this->assertSame($plugin$this->searchPluginCollection->get('banana'));
  }

}
->method('handle')
            ->willReturnCallback(static function DRequest $request) {
                if ($request->getRequestUri() === '/product/list?page=1' || $request->getRequestUri() === '/product/list?page=2') {
                    return new Response();
                }

                throw new \RuntimeException('Unexpected request');
            });

        $this->kernel->expects(static::once())
            ->method('reboot')
            ->with(null, null, 'cacheId');

        $container = new Container();
        $container->set(CacheStore::class$this->createMock(CacheStore::class));

        $this->kernel->expects(static::once())
            ->method('getContainer')
            ->willReturn($container);

        $message = new WarmUpMessage(
            'product.list',
            [['page' => '1']['page' => '2']],
        );
->method('getExtra')
      ->willReturn([]);

    // The default is to try to read from event-name-message.txt, so we expect     // config to try that.     $message = $this->getMockBuilder(Message::class)
      ->setConstructorArgs([$root, 'event-name'])
      ->onlyMethods(['getMessageFromFile'])
      ->getMock();
    $message->expects($this->once())
      ->method('getMessageFromFile')
      ->with('event-name-message.txt')
      ->willReturn([]);

    $this->assertSame([]$message->getText());
  }

}
$this->connection->expects(static::once())->method('fetchAssociative')->willReturn($existedData);
        $this->flow->expects(static::exactly(2))->method('getData')->willReturn(Uuid::randomHex());
        $this->flow->expects(static::once())->method('hasData')->willReturn(true);
        $this->flow->expects(static::once())->method('getConfig')->willReturn($config);

        $withData = [[...[
            'id' => $this->flow->getData('orderId'),
        ], ...$expected]];

        $this->repository->expects(static::once())
            ->method('update')
            ->with($withData);

        $this->action->handleFlow($this->flow);
    }

    public function testActionWithNotAware(): void
    {
        $this->flow->expects(static::once())->method('hasData')->willReturn(false);
        $this->flow->expects(static::never())->method('getData');
        $this->repository->expects(static::never())->method('update');

        $this->action->handleFlow($this->flow);
    }
public function testAccountRegister(): void
    {
        $context = Generator::createSalesChannelContext();
        $context->assign(['customer' => null]);
        $request = new Request();
        $request->attributes->set('_route', 'frontend.account.login.page');
        $dataBag = new RequestDataBag();
        $page = new AccountLoginPage();

        $this->accountLoginPageLoader->expects(static::once())
            ->method('load')
            ->with($request$context)
            ->willReturn($page);

        $this->controller->loginPage($request$dataBag$context);

        static::assertSame($page$this->controller->renderStorefrontParameters['page']);
        static::assertSame($dataBag$this->controller->renderStorefrontParameters['data']);
        static::assertSame('frontend.account.home.page', $this->controller->renderStorefrontParameters['redirectTo'] ?? '');
        static::assertSame('[]', $this->controller->renderStorefrontParameters['redirectParameters'] ?? '');
        static::assertSame('frontend.account.login.page', $this->controller->renderStorefrontParameters['errorRoute'] ?? '');
        static::assertInstanceOf(AccountLoginPageLoadedHook::class$this->controller->calledHook);
    }

    
$this->request->attributes = new ParameterBag(['_stateless' => false]);
        $this->request->expects($this->any())->method('getSession')->willReturn($this->session);
        $this->exception = $this->getMockBuilder(AuthenticationException::class)->onlyMethods(['getMessage'])->getMock();
    }

    public function testForward()
    {
        $options = ['failure_forward' => true];

        $subRequest = $this->getRequest();
        $subRequest->attributes->expects($this->once())
            ->method('set')->with(SecurityRequestAttributes::AUTHENTICATION_ERROR, $this->exception);
        $this->httpUtils->expects($this->once())
            ->method('createRequest')->with($this->request, '/login')
            ->willReturn($subRequest);

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options$this->logger);
        $result = $handler->onAuthenticationFailure($this->request, $this->exception);

        $this->assertSame($this->response, $result);
    }

    public function testRedirect()
    {
$schema = new Schema();
        $dbalConnection = $this->createMock(Connection::class);
        $entityManager = $this->createMock(EntityManagerInterface::class);
        $entityManager->expects($this->once())
            ->method('getConnection')
            ->willReturn($dbalConnection);
        $event = new GenerateSchemaEventArgs($entityManager$schema);

        $pdoSessionHandler = $this->createMock(PdoSessionHandler::class);
        $pdoSessionHandler->expects($this->once())
            ->method('configureSchema')
            ->with($schemafn () => true);

        $subscriber = new PdoSessionHandlerSchemaListener($pdoSessionHandler);
        $subscriber->postGenerateSchema($event);
    }
}
$_SERVER[MigrationStep::INSTALL_ENVIRONMENT_VARIABLE],
            $_ENV[MigrationStep::INSTALL_ENVIRONMENT_VARIABLE],
        );
    }

    public function testImportDatabaseRedirectsToConfigPageWhenDatabaseConnectionWasNotConfigured(): void
    {
        $this->twig->expects(static::never())
            ->method('render');

        $this->router->expects(static::once())->method('generate')
            ->with('installer.database-configuration', [], UrlGeneratorInterface::ABSOLUTE_PATH)
            ->willReturn('/installer/database-configuration');

        $session = new Session(new MockArraySessionStorage());
        $request = Request::create('/installer/database-import');
        $request->setSession($session);

        $response = $this->controller->databaseImport($request);
        static::assertInstanceOf(RedirectResponse::class$response);
        static::assertSame('/installer/database-configuration', $response->getTargetUrl());
    }

    
->method('generate')
            ->willReturn('http://example.com');

        $this->salesChannelContextService
            ->expects(static::once())
            ->method('get')
            ->willReturn($this->createMock(SalesChannelContext::class));

        $this->dispatcher
            ->expects(static::once())
            ->method('dispatch')
            ->with(
                static::isInstanceOf(UserRecoveryRequestEvent::class),
                UserRecoveryRequestEvent::EVENT_NAME
            );

        $service = new UserRecoveryService(
            $recoveryRepository,
            $userRepository,
            $this->router,
            $this->dispatcher,
            $this->salesChannelContextService,
            $salesChannelRepository
        );
protected $renderer;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $element_info_manager = $this->createMock('Drupal\Core\Render\ElementInfoManagerInterface');
    $element_info_manager->expects($this->any())
      ->method('getInfo')
      ->with('ajax')
      ->willReturn([
        '#header' => TRUE,
        '#commands' => [],
        '#error' => NULL,
      ]);
    $renderer = $this->createMock(RendererInterface::class);
    $renderer->expects($this->any())
      ->method('renderRoot')
      ->willReturnCallback(function D&$elements$is_root_call = FALSE) {
        $elements += ['#attached' => []];
        if (isset($elements['#markup'])) {
          
$request = Request::create('/', 'GET', []['_remember_me_cookie' => '0']);
        yield [$request, false];
    }

    public function testAuthenticate()
    {
        $rememberMeDetails = new RememberMeDetails(InMemoryUser::class, 'wouter', 1, 'secret');
        $request = Request::create('/', 'GET', []['_remember_me_cookie' => $rememberMeDetails->toString()]);
        $passport = $this->authenticator->authenticate($request);

        $this->rememberMeHandler->expects($this->once())->method('consumeRememberMeCookie')->with($this->callback(fn ($arg) => $rememberMeDetails == $arg));
        $passport->getUser(); // trigger the user loader     }

    public function testAuthenticateWithoutToken()
    {
        $this->expectException(\LogicException::class);

        $this->authenticator->authenticate(Request::create('/'));
    }

    public function testAuthenticateWithoutOldToken()
    {
// The mail is still set to the value from the beginning.     $this->assertEquals('config@drupal.example', $exported['mail']);
  }

  /** * Tests the export storage when it is locked. */
  public function testGetStorageLock() {
    $lock = $this->createMock('Drupal\Core\Lock\LockBackendInterface');
    $lock->expects($this->exactly(2))
      ->method('acquire')
      ->with(ExportStorageManager::LOCK_NAME)
      ->willReturn(FALSE);
    $lock->expects($this->once())
      ->method('wait')
      ->with(ExportStorageManager::LOCK_NAME);

    // The export storage manager under test.     $manager = new ExportStorageManager(
      $this->container->get('config.storage'),
      $this->container->get('database'),
      $this->container->get('event_dispatcher'),
      $lock
    );
Home | Imprint | This part of the site doesn't use cookies.