【问题标题】:I would like to ask about PHPUnit of Drupal 8我想问一下 Drupal 8 的 PHPUnit
【发布时间】:2018-08-08 00:00:15
【问题描述】:

我在 Drupal 8 中使用自定义模块创建了 Block。

是否可以用 PHPUnit 来实现? 如果你能实现它,请告诉我如何实现。

我想用下面的PHPUnit实现测试。

如果您能回答是否可能,我会很高兴。

模块名称块.php

/**
 * @file
 * create block
 */

namespace Drupal\moduleName\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;

/**
 *
 * Provides a 'testBlock' block.
 * @Block(
 *   id = "test_block",
 *   admin_label = @Translation("Test"),
 *   category = @Translation("Menu"),
 * )
 */
class moduleNameBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build()
  {
    $build = [];
    $url   = '';
    $nid   = '';

    $nid = $this->getCurrentUserNode();
    if ( !empty($nid) ) {
      $url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
    }
    $block = [
      '#theme' => 'block_theme',
      '#url'   => $url,
      '#nid'   => $nid,
      '#cache' => [
        'max-age' => 0
      ]
    ];
    $build['test_block'] = $block;
    return $build;
  }

  /**
   * The node associated with the user
   * @return nid
   */
  private function getCurrentUserNode() {
    $user_id = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $nid     = $user_id->get('field_name')->getValue();

    return $nid[0]['target_id'];
  }  
}

【问题讨论】:

    标签: drupal phpunit drupal-8


    【解决方案1】:

    是的,这可以通过编写 PHPUnit 功能测试来实现。

    在您的模块目录中创建以下结构/tests/src/Functional,然后创建一个类似ModuleNameBlockTest.php 的文件,然后您可以将块放在setUp 函数中并创建测试来测试块。

    <?php
    
    namespace Drupal\Tests\my_module_name\Functional;
    
    use Drupal\Tests\BrowserTestBase;
    
    /**
     * Class ModuleNameBlockTest.
     *
     * @package Drupal\Tests\my_module_name\Functional
     * @group my_group
     */
    class ModuleNameBlockTest extends BrowserTestBase {
    
      /**
       * Modules to enable.
       *
       * @var array
       */
      public static $modules = ['block', 'my_module_name'];
    
      /**
       * {@inheritdoc}
       */
      protected function setUp() {
        parent::setUp();
        $adminUser = $this->drupalCreateUser(['administer blocks']);
        $this->drupalLogin($adminUser);
        $this->drupalPlaceBlock('my_block_name');
        $this->drupalLogout($adminUser);
      }
    
      /**
       * Test the block.
       */
      public function testMyAwesomeBlock() {
        // Your test logic here.
      }
    
    }
    

    您可以随时查看 Drupal 的源代码以获取一些示例。例如。核心用户模块的UserBlocksTest.php。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-06
      • 2021-12-24
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 2015-11-20
      • 2016-01-22
      相关资源
      最近更新 更多