willReturnCallback example

/** * Tests the formatInterval method. * * @dataProvider providerTestFormatInterval * * @covers ::formatInterval */
  public function testFormatInterval($interval$granularity$expected$langcode = NULL) {
    // Mocks a simple formatPlural implementation.     $this->stringTranslation->expects($this->any())
      ->method('translateString')
      ->willReturnCallback(function DTranslatableMarkup $arg) {
        return $arg->getUntranslatedString();
      });

    // Check if the granularity is specified.     if ($granularity) {
      $result = $this->dateFormatter->formatInterval($interval$granularity$langcode);
    }
    else {
      $result = $this->dateFormatter->formatInterval($interval);
    }

    
$route_2 = new Route('test_route/example', ['_controller' => 'Drupal\Tests\Core\Controller\TestController']);
    $collection->add('test_route_2', $route_2);

    $route_event = new RouteBuildEvent($collection);

    [$display_1$display_2] = $this->setupMocks();

    // The page_1 display overrides an existing route, so the dynamicRoutes     // should only call the second display.     $display_1->expects($this->once())
      ->method('collectRoutes')
      ->willReturnCallback(function D) use ($collection) {
        $collection->add('views.test_id.page_1', new Route('test_route', ['_controller' => 'Drupal\views\Routing\ViewPageController']));
        return ['test_id.page_1' => 'views.test_id.page_1'];
      });
    $display_1->expects($this->once())
      ->method('alterRoutes')
      ->willReturn(['test_id.page_1' => 'test_route']);

    $display_2->expects($this->once())
      ->method('collectRoutes')
      ->willReturnCallback(function D) use ($collection) {
        $collection->add('views.test_id.page_2', new Route('test_route', ['_controller' => 'Drupal\views\Routing\ViewPageController']));
        
$this->messenger->expects($this->exactly(4))
      ->method('addError')
      ->withConsecutive(
        ['no title given', FALSE],
        ['element is invisible', FALSE],
        ['this missing element is invalid', FALSE],
        ['3 errors have been found: <ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>', FALSE],
      );

    $this->renderer->expects($this->once())
      ->method('renderPlain')
      ->willReturnCallback(function D$render_array) {
        $links = [];
        foreach ($render_array[1]['#items'] as $item) {
          $links[] = htmlspecialchars($item['#title']);
        }

        return $render_array[0]['#markup'] . '<ul-comma-list-mock><li-mock>' . implode('</li-mock><li-mock>', $links) . '</li-mock></ul-comma-list-mock>';
      });

    $form_state = new FormState();
    $form_state->setErrorByName('test1', 'invalid');
    $form_state->setErrorByName('test2', 'invalid');
    
$compilers[] = $extraCompiler;
        }

        $compiler = new AssetMapperCompiler(
            $compilers,
            fn () => $this->assetMapper,
        );

        $pathResolver = $this->createMock(PublicAssetsPathResolverInterface::class);
        $pathResolver->expects($this->any())
            ->method('resolvePublicPath')
            ->willReturnCallback(function Dstring $logicalPath) {
                return '/final-assets/'.$logicalPath;
            });

        $factory = new MappedAssetFactory(
            $pathResolver,
            $compiler
        );

        // mock the AssetMapper to behave like normal: by calling back to the factory         $this->assetMapper = $this->createMock(AssetMapperInterface::class);
        $this->assetMapper->expects($this->any())
            
'product',
                3,
                new ProductCollection([$product1$product2$product3]),
                null,
                $criteria,
                $context->getContext()
            );

            return new ProductListResponse($searchResult);
        };

        $this->productListRouteMock->expects(static::once())->method('load')->willReturnCallback($productRouteLoadClosure);

        $context = $this->salesChannelContextMock;

        $eventDidRun = null;
        $phpunit = $this;
        $listenerClosure = function DGuestWishlistPageletLoadedEvent $event) use (
            &$eventDidRun,
            $phpunit,
            $context,
            $request
        ): void {
            
$productId => $lineItemData,
                    $productId2 => $lineItemData2,
                ],
            ]
        );

        $cart = new Cart(Uuid::randomHex());
        $context = $this->createMock(SalesChannelContext::class);

        $matcher = static::exactly(2);
        $this->lineItemRegistryMock->expects($matcher)->method('create')
            ->willReturnCallback(
                function Darray $lineItemDataPar, SalesChannelContext $contextPar) use (
                    $matcher,
                    $expectedLineItemData,
                    $expectedLineItemData2
                ) {
                    match ($matcher->getInvocationCount()) {
                        default => static::fail('to many calls of create'),
                        2 => static::assertEquals($expectedLineItemData2$lineItemDataPar),
                        1 => static::assertEquals($expectedLineItemData$lineItemDataPar),
                    };

                    
public function testDecideLog(array $expectedLog, array $attributes$object, array $voterVotes, bool $result)
    {
        $token = $this->createMock(TokenInterface::class);
        $admMock = $this->createMock(AccessDecisionManagerInterface::class);

        $adm = new TraceableAccessDecisionManager($admMock);

        $admMock
            ->expects($this->once())
            ->method('decide')
            ->with($token$attributes$object)
            ->willReturnCallback(function D$token$attributes$object) use ($voterVotes$adm$result) {
                foreach ($voterVotes as $voterVote) {
                    [$voter$vote] = $voterVote;
                    $adm->addVoterVote($voter$attributes$vote);
                }

                return $result;
            })
        ;

        $adm->decide($token$attributes$object);

        

  public function testBuildWithTwoPathElements() {
    $this->context->expects($this->once())
      ->method('getPathInfo')
      ->willReturn('/example/baz');
    $this->setupStubPathProcessor();

    $route_1 = new Route('/example');

    $this->requestMatcher->expects($this->exactly(1))
      ->method('matchRequest')
      ->willReturnCallback(function DRequest $request) use ($route_1) {
        if ($request->getPathInfo() == '/example') {
          return [
            RouteObjectInterface::ROUTE_NAME => 'example',
            RouteObjectInterface::ROUTE_OBJECT => $route_1,
            '_raw_variables' => new InputBag([]),
          ];
        }
      });

    $this->setupAccessManagerToAllow();

    
->with('id')->willReturn('data');
        $proxy = new StrictSessionHandler($handler);

        $this->assertTrue($proxy->validateId('id'));
        $this->assertSame('data', $proxy->read('id'));
    }

    public function testReadWithValidateIdMismatch()
    {
        $handler = $this->createMock(\SessionHandlerInterface::class);
        $handler->expects($this->exactly(2))->method('read')
            ->willReturnCallback(function D...$args) {
                static $series = [
                    [['id1'], 'data1'],
                    [['id2'], 'data2'],
                ];

                [$expectedArgs$return] = array_shift($series);
                $this->assertSame($expectedArgs$args);

                return $return;
            })
        ;
        

class ElasticsearchLanguageProviderTest extends TestCase
{
    public function testGetLanguages(): void
    {
        $languageRepository = $this->createMock(EntityRepository::class);

        $languageRepository
            ->method('search')
            ->willReturnCallback(function DCriteria $criteria) {
                static::assertTrue($criteria->hasEqualsFilter('fooo'));
                $sortings = $criteria->getSorting();
                static::assertCount(1, $sortings);
                static::assertEquals('id', $sortings[0]->getField());

                return new EntitySearchResult('foo', 0, new LanguageCollection(), null, $criteria, Context::createDefaultContext());
            });

        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(ElasticsearchIndexerLanguageCriteriaEvent::classfunction DElasticsearchIndexerLanguageCriteriaEvent $event): void {
            $event->getCriteria()->addFilter(new EqualsFilter('fooo', null));
        });
class FailedMessagesRetryCommandTest extends TestCase
{
    public function testBasicRunWithServiceLocator()
    {
        $series = [
            [[10]new Envelope(new \stdClass())],
            [[12]new Envelope(new \stdClass())],
        ];

        $receiver = $this->createMock(ListableReceiverInterface::class);
        $receiver->expects($this->exactly(2))->method('find')
            ->willReturnCallback(function D...$args) use (&$series) {
                [$expectedArgs$return] = array_shift($series);
                $this->assertSame($expectedArgs$args);

                return $return;
            })
        ;

        // message will eventually be ack'ed in Worker         $receiver->expects($this->exactly(2))->method('ack');

        $dispatcher = new EventDispatcher();
        
$this->templateManager->getName(new Profile('token'), 'notexistingpanel');
    }

    /** * if template exists in both profile and profiler then its name should be returned. */
    public function testGetNameValidTemplate()
    {
        $this->profiler->expects($this->any())
            ->method('has')
            ->withAnyParameters()
            ->willReturnCallback($this->profilerHasCallback(...));

        $this->assertEquals('@Foo/Collector/foo.html.twig', $this->templateManager->getName(new ProfileDummy(), 'foo'));
    }

    public function profilerHasCallback($panel)
    {
        return match ($panel) {
            'foo',
            'bar' => true,
            default => false,
        };
    }
/** * Tests the applies() method. * * @dataProvider providerTestApplies * * @covers ::applies */
  public function testApplies(array $definition$name, Route $route$applies) {
    $this->entityTypeManager->expects($this->any())
      ->method('hasDefinition')
      ->willReturnCallback(function D$entity_type) {
        return 'entity_test' == $entity_type;
      });
    $this->assertEquals($applies$this->entityConverter->applies($definition$name$route));
  }

  /** * Provides test data for testApplies() */
  public function providerTestApplies() {
    $data = [];
    $data[] = [['type' => 'entity:foo'], 'foo', new Route('/test/{foo}/bar'), FALSE];
    
/** * @dataProvider provideConstraintsWithCustomRepositoryMethod */
    public function testValidateUniquenessWithUnrewoundArray(UniqueEntity $constraint)
    {
        $entity = new SingleIntIdEntity(1, 'foo');

        $repository = $this->createRepositoryMock();
        $repository->expects($this->once())
            ->method('findByCustom')
            ->willReturnCallback(
                function D) use ($entity) {
                    $returnValue = [
                        $entity,
                    ];
                    next($returnValue);

                    return $returnValue;
                }
            )
        ;
        $this->em = $this->createEntityManagerMock($repository);
        


    public function testWarmupRemoveCacheMisses()
    {
        $cacheFile = tempnam($this->cacheDir, __FUNCTION__);
        $this->expectDeprecation('Since symfony/framework-bundle 6.4: The "Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer" class is deprecated without replacement.');
        $warmer = $this->getMockBuilder(AnnotationsCacheWarmer::class)
            ->setConstructorArgs([new AnnotationReader()$cacheFile])
            ->onlyMethods(['doWarmUp'])
            ->getMock();

        $warmer->method('doWarmUp')->willReturnCallback(function D$cacheDir, ArrayAdapter $arrayAdapter) {
            $arrayAdapter->getItem('foo_miss');

            $item = $arrayAdapter->getItem('bar_hit');
            $item->set('data');
            $arrayAdapter->save($item);

            $item = $arrayAdapter->getItem('baz_hit_null');
            $item->set(null);
            $arrayAdapter->save($item);

            return true;
        });
Home | Imprint | This part of the site doesn't use cookies.