getMockBuilder example


  protected function getMigration($id_map = NULL) {
    $this->migrationConfiguration += ['migrationClass' => 'Drupal\migrate\Plugin\Migration'];
    $this->idMap = $id_map;
    if (is_null($id_map)) {
      $this->idMap = $this->createMock(MigrateIdMapInterface::class);
      $this->idMap
        ->method('getQualifiedMapTableName')
        ->willReturn('test_map');
    }

    $migration = $this->getMockBuilder($this->migrationConfiguration['migrationClass'])
      ->disableOriginalConstructor()
      ->getMock();

    $migration->method('checkRequirements')
      ->willReturn(TRUE);

    $migration->method('getIdMap')
      ->willReturn($this->idMap);

    // We need the state to be toggled throughout the test so we store the value     // on the test class and use a return callback.

  protected $policy;

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

    // Note that it is necessary to partially mock the class under test in     // order to disable the isCli-check.     $this->policy = $this->getMockBuilder('Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod')
      ->onlyMethods(['isCli'])
      ->getMock();
  }

  /** * Asserts that check() returns DENY for unsafe HTTP methods. * * @dataProvider providerTestHttpMethod * @covers ::check */
  public function testHttpMethod($expected_result$method) {
    
$path = $this->urlGenerator->getRelativeThumbnailUrl($media$thumbnail);
            static::assertTrue(
                $this->getPublicFilesystem()->has($path),
                'Thumbnail: ' . $path . ' does not exist'
            );
        }
    }

    public function testDiffersBetweenUpdateAndGenerateMessage(): void
    {
        $thumbnailServiceMock = $this->getMockBuilder(ThumbnailService::class)
            ->disableOriginalConstructor()->getMock();

        $handler = new GenerateThumbnailsHandler($thumbnailServiceMock$this->mediaRepository);

        $randomCriteria = (new Criteria())
            /* @see GenerateThumbnailsHandler Association as in target method is required for the ease of PHPUnit's constraint evaluation */
            ->addAssociation('mediaFolder.configuration.mediaThumbnailSizes')
            ->setLimit(5);

        $testEntities1 = $this->mediaRepository->search($randomCriteria->setOffset(0)$this->context)->getEntities();
        $testEntities2 = $this->mediaRepository->search($randomCriteria->setOffset(5)$this->context)->getEntities();
        
$entity_type_manager->expects($this->once())
      ->method('getStorage')
      ->with('action')
      ->willReturn($entity_storage);

    $entity_repository = $this->createMock(EntityRepositoryInterface::class);

    $language_manager = $this->createMock('Drupal\Core\Language\LanguageManagerInterface');

    $messenger = $this->createMock('Drupal\Core\Messenger\MessengerInterface');

    $views_data = $this->getMockBuilder('Drupal\views\ViewsData')
      ->disableOriginalConstructor()
      ->getMock();
    $views_data->expects($this->any())
      ->method('get')
      ->with('node')
      ->willReturn(['table' => ['entity type' => 'node']]);
    $container = new ContainerBuilder();
    $container->set('views.views_data', $views_data);
    $container->set('string_translation', $this->getStringTranslationStub());
    \Drupal::setContainer($container);

    

    public function testInvalidation(\Closure $before, \Closure $after, int $calls): void
    {
        $this->getContainer()->get('cache.object')
            ->invalidateTags([CachedSalutationRoute::ALL_TAG]);

        $route = $this->getContainer()->get(SalutationRoute::class);

        static::assertInstanceOf(CachedSalutationRoute::class$route);

        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $listener = $this->getMockBuilder(CallableClass::class)->getMock();

        $listener->expects(static::exactly($calls))->method('__invoke');
        $this->addEventListener($dispatcher, 'salutation.loaded', $listener);

        $before($this->getContainer());

        $route->load(new Request()$this->context, new Criteria());
        $route->load(new Request()$this->context, new Criteria());

        $after($this->getContainer());

        

  public function testHasMatchingRoute($routes$route_name$route_params$result) {
    $tour = $this->getMockBuilder('\Drupal\tour\Entity\Tour')
      ->disableOriginalConstructor()
      ->onlyMethods(['getRoutes'])
      ->getMock();

    $tour->expects($this->any())
      ->method('getRoutes')
      ->willReturn($routes);

    $this->assertSame($result$tour->hasMatchingRoute($route_name$route_params));

    $tour->resetKeyedRoutes();
  }

    public function testInvalidation(\Closure $before, \Closure $after, int $calls): void
    {
        $this->getContainer()->get('cache.object')
            ->invalidateTags([CachedCountryRoute::buildName(TestDefaults::SALES_CHANNEL)]);

        $route = $this->getContainer()->get(CountryRoute::class);

        static::assertInstanceOf(CachedCountryRoute::class$route);

        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $listener = $this->getMockBuilder(CallableClass::class)->getMock();

        $listener->expects(static::exactly($calls))->method('__invoke');
        $this->addEventListener($dispatcher, 'country.loaded', $listener);

        $before($this->getContainer());

        $route->load(new Request()new Criteria()$this->context);
        $route->load(new Request()new Criteria()$this->context);

        $after($this->getContainer());

        
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Event\VoteEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

class TraceableVoterTest extends TestCase
{
    public function testGetDecoratedVoterClass()
    {
        $voter = $this->getMockBuilder(VoterInterface::class)->getMockForAbstractClass();

        $sut = new TraceableVoter($voter$this->getMockBuilder(EventDispatcherInterface::class)->getMockForAbstractClass());
        $this->assertSame($voter$sut->getDecoratedVoter());
    }

    public function testVote()
    {
        $voter = $this->getMockBuilder(VoterInterface::class)->getMockForAbstractClass();

        $eventDispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMockForAbstractClass();
        $token = $this->getMockBuilder(TokenInterface::class)->getMockForAbstractClass();

        

class AdminSearchControllerTest extends TestCase
{
    private AdminSearcher $searcher;

    protected function setUp(): void
    {
        $this->searcher = $this->getMockBuilder(AdminSearcher::class)->disableOriginalConstructor()->getMock();

        $promotion = new PromotionEntity();
        $promotion->setUniqueIdentifier(Uuid::randomHex());
        $this->searcher->method('search')->willReturn([
            'promotion' => [
                'total' => 1,
                'data' => new EntityCollection([$promotion]),
                'indexer' => 'promotion-listing',
                'index' => 'sw-admin-promotion-listing',
            ],
        ]);
    }

      ],
    ];
  }

  /** * @dataProvider provideGetMessageText * @covers ::getText */
  public function testGetMessageText($expected$config) {
    // Root package has our config.     $root = $this->getMockBuilder(RootPackageInterface::class)
      ->onlyMethods(['getExtra'])
      ->getMockForAbstractClass();
    $root->expects($this->once())
      ->method('getExtra')
      ->willReturn($config);

    $message = new Message($root, 'event-name');

    $this->assertSame($expected$message->getText());
  }

  

class ForumListingBreadcrumbBuilderTest extends UnitTestCase {

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

    $cache_contexts_manager = $this->getMockBuilder('Drupal\Core\Cache\Context\CacheContextsManager')
      ->disableOriginalConstructor()
      ->getMock();
    $cache_contexts_manager->method('assertValidTokens')->willReturn(TRUE);
    $container = new Container();
    $container->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($container);
  }

  /** * Tests ForumListingBreadcrumbBuilder::applies(). * * @param bool $expected * ForumListingBreadcrumbBuilder::applies() expected result. * @param string|null $route_name * (optional) A route name. * @param array $parameter_map * (optional) An array of parameter names and values. * * @dataProvider providerTestApplies * @covers ::applies */

    protected $loader;

    protected function setUp(): void
    {
        $this->loader = $this->getContainer()->get(NavigationLoader::class);
        parent::setUp();
    }

    public function testEventDispatched(): void
    {
        $listener = $this->getMockBuilder(CallableClass::class)->getMock();
        $listener->expects(static::once())->method('__invoke');

        $dispatcher = $this->getContainer()->get('event_dispatcher');
        $this->addEventListener($dispatcher, NavigationLoadedEvent::class$listener);

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $navigationId = $context->getSalesChannel()->getNavigationCategoryId();

        $this->loader->load($navigationId$context$navigationId);
    }
public function testAvoidInfiniteLoopEventsWithLotsOfPromotions(): void
    {
        $productId = Uuid::randomHex();

        $this->createTestFixtureProduct($productId, 119, 19, $this->getContainer()$this->getContext());

        $codes = [100, 1, 42, 13, 19];
        $this->createBulkPromotions($codes);

        $dispatcher = $this->getContainer()->get('event_dispatcher');

        $addListener = $this->getMockBuilder(CallableClass::class)->getMock();
        $addListener->expects(static::exactly(1 + \count($codes)))->method('__invoke');
        $this->addEventListener($dispatcher, BeforeLineItemAddedEvent::class$addListener);

        $cart = $this->cartService->getCart($this->getContext()->getToken()$this->getContext());

        // add all our prepared test fixtures         // and promotions to our current cart.         foreach ($codes as $code) {
            $cart = $this->addPromotionCode((string) $code$cart$this->cartService, $this->getContext());
        }

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

    $cache_backend = new NullBackend('cache');
    $namespaces = new \ArrayObject([
      'Drupal\\Core\\TypedData' => $this->root . '/core/lib/Drupal/Core/TypedData',
      'Drupal\\Core\\Validation' => $this->root . '/core/lib/Drupal/Core/Validation',
    ]);
    $module_handler = $this->getMockBuilder('Drupal\Core\Extension\ModuleHandlerInterface')
      ->disableOriginalConstructor()
      ->getMock();
    $class_resolver = $this->getMockBuilder('Drupal\Core\DependencyInjection\ClassResolverInterface')
      ->disableOriginalConstructor()
      ->getMock();

    $this->typedDataManager = new TypedDataManager($namespaces$cache_backend$module_handler$class_resolver);
    $this->typedDataManager->setValidationConstraintManager(
      new ConstraintManager($namespaces$cache_backend$module_handler)
    );
    // Typed data definitions access the manager in the container.
$entity_type_manager->expects($this->once())
      ->method('getStorage')
      ->with('action')
      ->willReturn($entity_storage);

    $entity_repository = $this->createMock(EntityRepositoryInterface::class);

    $language_manager = $this->createMock('Drupal\Core\Language\LanguageManagerInterface');

    $messenger = $this->createMock('Drupal\Core\Messenger\MessengerInterface');

    $views_data = $this->getMockBuilder('Drupal\views\ViewsData')
      ->disableOriginalConstructor()
      ->getMock();
    $views_data->expects($this->any())
      ->method('get')
      ->with('comment')
      ->willReturn(['table' => ['entity type' => 'comment']]);
    $container = new ContainerBuilder();
    $container->set('views.views_data', $views_data);
    $container->set('string_translation', $this->getStringTranslationStub());
    \Drupal::setContainer($container);

    
Home | Imprint | This part of the site doesn't use cookies.