addMethods example

$form_validator->validateForm('test_form_id', $form$form_state);
  }

  /** * @covers ::performRequiredValidation * * @dataProvider providerTestPerformRequiredValidation */
  public function testPerformRequiredValidation($element$expected_message$call_watchdog) {
    $form_validator = $this->getMockBuilder('Drupal\Core\Form\FormValidator')
      ->setConstructorArgs([new RequestStack()$this->getStringTranslationStub()$this->csrfToken, $this->logger, $this->formErrorHandler])
      ->addMethods(['setError'])
      ->getMock();

    if ($call_watchdog) {
      $this->logger->expects($this->once())
        ->method('error')
        ->with($this->isType('string')$this->isType('array'));
    }

    $form = [];
    $form['test'] = $element + [
      '#title' => 'Test',
      
$values = ['targetEntityType' => $target_entity_type_id];

    $this->entityTypeManager->expects($this->exactly(2))
      ->method('getDefinition')
      ->willReturnMap([
        [$target_entity_type_id, TRUE, $target_entity_type],
        [$this->entityType, TRUE, $this->entityInfo],
      ]);

    $this->entity = $this->getMockBuilder('\Drupal\Core\Entity\EntityDisplayModeBase')
      ->setConstructorArgs([$values$this->entityType])
      ->addMethods(['getFilterFormat'])
      ->getMock();

    $dependencies = $this->entity->calculateDependencies()->getDependencies();
    $this->assertContains('test_module', $dependencies['module']);
  }

  /** * @covers ::setTargetType */
  public function testSetTargetType() {
    // Generate mock.
->with($this->equalTo(self::EM_NAME))
                 ->willReturn($em);

        return $registry;
    }

    protected function createRepositoryMock()
    {
        $repository = $this->getMockBuilder(EntityRepository::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['find', 'findAll', 'findOneBy', 'findBy', 'getClassName'])
            ->addMethods(['findByCustom'])
            ->getMock()
        ;

        return $repository;
    }

    protected function createEntityManagerMock($repositoryMock)
    {
        $em = $this->createMock(ObjectManager::class);
        $em->expects($this->any())
            ->method('getRepository')
            
$container->set('cache_contexts_manager', $cache_context_manager);
    $cache_context_manager->expects($this->any())
      ->method('assertValidTokens')
      ->willReturn(TRUE);
    \Drupal::setContainer($container);

    $this->blockRepository = $this->createMock('Drupal\block\BlockRepositoryInterface');
    $this->blockViewBuilder = $this->createMock('Drupal\Core\Entity\EntityViewBuilderInterface');

    return $this->getMockBuilder('Drupal\block\Plugin\DisplayVariant\BlockPageVariant')
      ->setConstructorArgs([$configuration, 'test', $definition$this->blockRepository, $this->blockViewBuilder, ['config:block_list']])
      ->addMethods(['getRegionNames'])
      ->getMock();
  }

  public function providerBuild() {
    $blocks_config = [
      'block1' => [
        // region, is main content block, is messages block, is title block         'top', FALSE, FALSE, FALSE,
      ],
      // Test multiple blocks in the same region.       'block2' => [
        
protected function getKernel(array $methods = [], array $bundles = [], bool $debug = false, array $methodsToAdd = []): Kernel
    {
        $methods[] = 'registerBundles';

        $kernelMockBuilder = $this
            ->getMockBuilder(KernelForTest::class)
            ->onlyMethods($methods)
            ->setConstructorArgs(['test', $debug])
        ;

        if (0 !== \count($methodsToAdd)) {
            $kernelMockBuilder->addMethods($methodsToAdd);
        }

        $kernel = $kernelMockBuilder->getMock();
        $kernel->expects($this->any())
            ->method('registerBundles')
            ->willReturn($bundles)
        ;

        return $kernel;
    }
}

throw new \Exception('dont break here <info>!</info>');
        });
        $tester = new ApplicationTester($application);

        $tester->run(['command' => 'foo']['decorated' => false]);
        $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting');
        putenv('COLUMNS=120');
    }

    public function testRenderExceptionLineBreaks()
    {
        $application = $this->getMockBuilder(Application::class)->addMethods(['getTerminalWidth'])->getMock();
        $application->setAutoExit(false);
        $application->expects($this->any())
            ->method('getTerminalWidth')
            ->willReturn(120);
        $application->register('foo')->setCode(function D) {
            throw new \InvalidArgumentException("\n\nline 1 with extra spaces \nline 2\n\nline 4\n");
        });
        $tester = new ApplicationTester($application);

        $tester->run(['command' => 'foo']['decorated' => false]);
        $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
    }


  /** * Sets up a test field. * * @return \Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField|\PHPUnit\Framework\MockObject\MockObject * The test field. */
  protected function setupTestField(array $options = []) {
    /** @var \Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField $field */
    $field = $this->getMockBuilder('Drupal\Tests\views\Unit\Plugin\field\FieldPluginBaseTestField')
      ->addMethods(['l'])
      ->setConstructorArgs([$this->configuration, $this->pluginId, $this->pluginDefinition])
      ->getMock();
    $field->init($this->executable, $this->display, $options);
    $field->setLinkGenerator($this->linkGenerator);

    return $field;
  }

  /** * @covers ::getRenderTokens */
  

  protected function setUp(): void {
    parent::setUp();

    $container = new ContainerBuilder();

    $request = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Request')
      ->disableOriginalConstructor()
      ->getMock();

    $view = $this->getMockBuilder('\Drupal\views\Entity\View')
      ->addMethods(['initHandlers'])
      ->setConstructorArgs([['id' => 'test_view'], 'view'])
      ->getMock();

    $view_executable = $this->getMockBuilder('\Drupal\views\ViewExecutable')
      ->onlyMethods(['initHandlers', 'getTitle'])
      ->disableOriginalConstructor()
      ->getMock();
    $view_executable->expects($this->any())
      ->method('getTitle')
      ->willReturn('View title');

    

        $this->expectException(\BadMethodCallException::class);
        $loader = new TestObjectLoader();
        $loader->loaderMap = ['my_service' => new \stdClass()];
        $loader->load('my_service::method');
    }

    public function testExceptionOnMethodNotReturningCollection()
    {
        $this->expectException(\LogicException::class);
        $service = $this->getMockBuilder(\stdClass::class)
            ->addMethods(['loadRoutes'])
            ->getMock();
        $service->expects($this->once())
            ->method('loadRoutes')
            ->willReturn('NOT_A_COLLECTION');

        $loader = new TestObjectLoader();
        $loader->loaderMap = ['my_service' => $service];
        $loader->load('my_service::loadRoutes');
    }
}

/** * @var \PHPUnit\Framework\MockObject\MockObject */
  protected $mockParser;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->mockParser = $this->getMockBuilder('\stdClass')
      ->addMethods(['encode', 'decode', 'getFileExtension'])
      ->getMock();
    YamlParserProxy::setMock($this->mockParser);
  }

  /** * {@inheritdoc} */
  protected function tearDown(): void {
    YamlParserProxy::setMock(NULL);
    parent::tearDown();
  }

  

  }

  /** * @covers ::getDefinition * @dataProvider providerGetDefinition */
  public function testGetDefinition($expected$has_register_definitions$exception_on_invalid$definitions$base_plugin_id) {
    // Mock our StaticDiscoveryDecorator.     $mock_decorator = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator')
      ->disableOriginalConstructor()
      ->addMethods(['registeredDefinitionCallback'])
      ->getMock();

    // Set up the ::$registerDefinitions property.     $ref_register_definitions = new \ReflectionProperty($mock_decorator, 'registerDefinitions');
    if ($has_register_definitions) {
      // Set the callback object on the mocked decorator.       $ref_register_definitions->setValue(
        $mock_decorator,
        [$this->getRegisterDefinitionsCallback(), 'registerDefinitionsCallback']
      );
    }
    


        $source = tempnam(sys_get_temp_dir(), 'source');

        $kernel = new TestHttpKernel();
        $client = new HttpKernelBrowser($kernel);

        $file = $this
            ->getMockBuilder(UploadedFile::class)
            ->setConstructorArgs([$source, 'original', 'mime/original', \UPLOAD_ERR_OK, true])
            ->onlyMethods(['getSize'])
            ->addMethods(['getClientSize'])
            ->getMock()
        ;
        /* should be modified when the getClientSize will be removed */
        $file->expects($this->any())
            ->method('getSize')
            ->willReturn(\PHP_INT_MAX)
        ;
        $file->expects($this->any())
            ->method('getClientSize')
            ->willReturn(\PHP_INT_MAX)
        ;

        
$usageIndex = $session->getUsageIndex();

        $tokenStorage = new TokenStorage();
        $listener = new ContextListener($tokenStorage[], 'context_key', null, null, null, $tokenStorage->getToken(...));
        $listener(new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST));

        $this->assertSame($usageIndex$session->getUsageIndex());
    }

    public function testSessionIsNotReported()
    {
        $usageReporter = $this->getMockBuilder(\stdClass::class)->addMethods(['__invoke'])->getMock();
        $usageReporter->expects($this->never())->method('__invoke');

        $session = new Session(new MockArraySessionStorage(), null, null, $usageReporter);

        $request = new Request();
        $request->setSession($session);
        $request->cookies->set('MOCKSESSID', true);

        $tokenStorage = new TokenStorage();

        $listener = new ContextListener($tokenStorage[], 'context_key', null, null, null, $tokenStorage->getToken(...));
        
Home | Imprint | This part of the site doesn't use cookies.