onlyMethods example

$this->cache->expects($this->once())
      ->method('get')
      ->with('locale:en:irrelevant:anonymous', FALSE);

    $this->storage->expects($this->once())
      ->method('findTranslation')
      ->with($this->equalTo($args))
      ->willReturn($result);

    $locale_lookup = $this->getMockBuilder('Drupal\locale\LocaleLookup')
      ->setConstructorArgs(['en', 'irrelevant', $this->storage, $this->cache, $this->lock, $this->configFactory, $this->languageManager, $this->requestStack])
      ->onlyMethods(['persist'])
      ->getMock();
    $locale_lookup->expects($this->never())
      ->method('persist');
    $this->assertSame('test', $locale_lookup->get('test'));
  }

  /** * Tests locale lookups with fallback. * * Note that context is irrelevant here. It is not used but it is required. * * @covers ::resolveCacheMiss * * @dataProvider resolveCacheMissWithFallbackProvider */
$item = $this->createMock(CacheItemInterface::class);
        $item->method('set')
            ->willReturn($item);
        $item->method('isHit')
            ->willReturn(false);

        $item->expects($this->once())
            ->method('set')
            ->with('computed data');

        $cache = $this->getMockBuilder(TestPool::class)
            ->onlyMethods(['getItem', 'save'])
            ->getMock();
        $cache->expects($this->once())
            ->method('getItem')
            ->with('key')
            ->willReturn($item);
        $cache->expects($this->once())
            ->method('save');

        $callback = function DCacheItemInterface $item) {
            return 'computed data';
        };

        
/** * Creates a mocked PhpMail object. * * The method "doMail()" gets overridden to avoid a mail() call in tests. * * @return \Drupal\Core\Mail\Plugin\Mail\PhpMail|\PHPUnit\Framework\MockObject\MockObject * A PhpMail instance. */
  protected function createPhpMailInstance(): PhpMail {
    $mailer = $this->getMockBuilder(PhpMail::class)
      ->onlyMethods(['doMail'])
      ->getMock();

    $request = $this->getMockBuilder(Request::class)
      ->disableOriginalConstructor()
      ->getMock();

    $request->server = $this->getMockBuilder(ServerBag::class)
      ->onlyMethods(['has', 'get'])
      ->getMock();

    $request->server->method('has')->willReturn(FALSE);
    

  public function testSuspendQueue(): void {
    [
      'queue_factory' => $queueFactory,
      'queue_manager' => $queueManager,
      'time' => $time,
    ] = $this->cronConstructorArguments;

    $cron = $this->getMockBuilder(Cron::class)
      ->onlyMethods(['usleep'])
      ->setConstructorArgs($this->cronConstructorArguments)
      ->getMock();

    $cron->expects($this->exactly(2))
      ->method('usleep')
      ->withConsecutive(
        [$this->equalTo(2000000)],
        [$this->equalTo(3000000)],
      );

    $queueManager->expects($this->once())
      
// does not implement TerminableInterface         $kernel = new TestKernel();
        $httpCache = new HttpCache($kernel$storeMock, null, ['terminate_on_cache_hit' => false]);
        $httpCache->terminate(Request::create('/')new Response());

        $this->assertFalse($kernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface');

        // implements TerminableInterface         $kernelMock = $this->getMockBuilder(Kernel::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['terminate', 'registerBundles', 'registerContainerConfiguration'])
            ->getMock();

        $kernelMock->expects($this->once())
            ->method('terminate');

        $kernel = new HttpCache($kernelMock$storeMock, null, ['terminate_on_cache_hit' => false]);
        $kernel->terminate(Request::create('/')new Response());
    }

    public function testDoesNotCallTerminateOnFreshResponse()
    {
        
// Mock the TypedDataManager to return a TypedDataInterface mock.     $this->typedData = $this->createMock('Drupal\Core\TypedData\TypedDataInterface');
    $typed_data_manager = $this->createMock(TypedDataManagerInterface::class);
    $typed_data_manager->expects($this->any())
      ->method('getPropertyInstance')
      ->willReturn($this->typedData);

    // Set up a mock container as ItemList() will call for the 'typed_data_manager'     // service.     $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
      ->onlyMethods(['get'])
      ->getMock();
    $container->expects($this->any())
      ->method('get')
      ->with($this->equalTo('typed_data_manager'))
      ->willReturn($typed_data_manager);

    \Drupal::setContainer($container);

    $this->normalizer = new ListNormalizer();

    $this->list = new ItemList(new DataDefinition());
    
/** * @internal */
class ProductDetailCmsElementResolverTest extends TestCase
{
    use IntegrationTestBehaviour;

    private MockObject&AbstractProductDetailCmsElementResolver $dummyResolver;

    protected function setUp(): void
    {
        $resolverMock = $this->getMockBuilder(AbstractProductDetailCmsElementResolver::class)->onlyMethods(['getType'])->getMockForAbstractClass();
        $resolverMock->method('getType')->willReturn('dummy-type');
        $this->dummyResolver = $resolverMock;
    }

    public function testCollectWithStaticConfig(): void
    {
        $resolverContext = new ResolverContext($this->createMock(SalesChannelContext::class)new Request());

        $fieldConfig = new FieldConfigCollection();
        $fieldConfig->add(new FieldConfig('product', FieldConfig::SOURCE_STATIC, 'product123'));

        
protected $messenger;

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

    $this->messenger = $this->createMock(MessengerInterface::class);

    $this->formErrorHandler = $this->getMockBuilder('Drupal\Core\Form\FormErrorHandler')
      ->onlyMethods(['messenger'])
      ->getMock();

    $this->formErrorHandler->expects($this->atLeastOnce())
      ->method('messenger')
      ->willReturn($this->messenger);
  }

  /** * @covers ::handleFormErrors * @covers ::displayErrorMessages */
  
$client->expects($this->never())->method('getQueueUrl');
        $client->expects($this->once())->method('deleteMessage');

        $connection->delete('id');
    }

    public function testLoggerWithoutDebugOption()
    {
        $client = new MockHttpClient([$this->getMockedQueueUrlResponse()$this->getMockedReceiveMessageResponse()]);
        $logger = $this->getMockBuilder(NullLogger::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['debug'])
            ->getMock();
        $logger->expects($this->never())->method('debug');
        $connection = Connection::fromDsn('sqs://default', ['access_key' => 'foo', 'secret_key' => 'bar', 'auto_setup' => false]$client$logger);
        $connection->get();
    }

    public function testLoggerWithDebugOption()
    {
        $client = new MockHttpClient([$this->getMockedQueueUrlResponse()$this->getMockedReceiveMessageResponse()]);
        $logger = $this->getMockBuilder(NullLogger::class)
            ->disableOriginalConstructor()
            
->setConstructorArgs([
                array_merge(
                    $connection->getParams(),
                    [
                        'url' => $_SERVER['DATABASE_URL'],
                        'dbname' => $connection->getDatabase(),
                    ]
                ),
                $connection->getDriver(),
                $connection->getConfiguration(),
            ])
            ->onlyMethods(['delete'])
            ->getMock();

        $connection->method('delete')->willThrowException(new Exception('test'));

        $successSpy = $this->callbackSpy();
        $errorSpy = $this->callbackSpy();

        $spy = $this->eventListenerCalledSpy(function DEntityDeleteEvent $event) use ($successSpy$errorSpy): void {
            $event->addSuccess($successSpy(...));
            $event->addError($errorSpy(...));
        });

        
$this->expectNotToPerformAssertions();

        $client = static::createClient(['test_case' => 'TestServiceContainer']);
        $client->request('GET', '/');
        static::ensureKernelShutdown();
        $client->request('GET', '/');
    }

    private function getKernelMock()
    {
        $mock = $this->getMockBuilder($this->getKernelClass())
            ->onlyMethods(['shutdown', 'boot', 'handle', 'getContainer'])
            ->disableOriginalConstructor()
            ->getMock();

        $mock->expects($this->any())->method('handle')->willReturn(new Response('foo'));

        return $mock;
    }
}
$this->assertEquals('ThePa$$word', $passport->getBadge(PasswordUpgradeBadge::class)->getAndErasePlaintextPassword());
    }

    public function testAddsNoPasswordUpgradeBadgeIfItAlreadyExists()
    {
        $hasher = $this->createMock(PasswordHasherInterface::class);
        $hasher->expects($this->any())->method('verify')->with('password-hash', 'ThePa$$word')->willReturn(true);

        $this->hasherFactory->expects($this->any())->method('getPasswordHasher')->with($this->identicalTo($this->user))->willReturn($hasher);

        $passport = $this->getMockBuilder(Passport::class)
            ->onlyMethods(['addBadge'])
            ->setConstructorArgs([new UserBadge('wouter', fn () => $this->user)new PasswordCredentials('ThePa$$word')[new PasswordUpgradeBadge('ThePa$$word')]])
            ->getMock();

        $passport->expects($this->never())->method('addBadge')->with($this->isInstanceOf(PasswordUpgradeBadge::class));

        $this->listener->checkPassport($this->createEvent($passport));
    }

    public function testAddsNoPasswordUpgradeBadgeIfPasswordIsInvalid()
    {
        $hasher = $this->createMock(PasswordHasherInterface::class);
        

  }

  /** * @covers ::get * @dataProvider providerGet */
  public function testGet($expected$field_name$active_langcode$fields) {
    // Mock ContentEntityBase.     $mock_base = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->onlyMethods(['getTranslatedField'])
      ->getMockForAbstractClass();

    // Set up expectations for getTranslatedField() method. In get(),     // getTranslatedField() is only called if the field name and language code     // are not present as keys in the fields array.     if (isset($fields[$field_name][$active_langcode])) {
      $mock_base->expects($this->never())
        ->method('getTranslatedField');
    }
    else {
      $mock_base->expects($this->once())
        
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\VarDumper\Cloner\Data;

class LoggerDataCollectorTest extends TestCase
{
    public function testCollectWithUnexpectedFormat()
    {
        $logger = $this
            ->getMockBuilder(DebugLoggerInterface::class)
            ->onlyMethods(['countErrors', 'getLogs', 'clear'])
            ->getMock();
        $logger->expects($this->once())->method('countErrors')->willReturn(123);
        $logger->expects($this->exactly(2))->method('getLogs')->willReturn([]);

        $c = new LoggerDataCollector($logger, __DIR__.'/');
        $c->lateCollect();
        $compilerLogs = $c->getCompilerLogs()->getValue('message');

        $this->assertSame([
            ['message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'],
            ['message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'],
        ],

  protected $sessionMetadata;

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

    $this->privateKey = $this->getMockBuilder('Drupal\Core\PrivateKey')
      ->disableOriginalConstructor()
      ->onlyMethods(['get'])
      ->getMock();

    $this->sessionMetadata = $this->getMockBuilder('Drupal\Core\Session\MetadataBag')
      ->disableOriginalConstructor()
      ->getMock();

    $settings = [
      'hash_salt' => $this->randomMachineName(),
    ];

    new Settings($settings);

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