Drupal8 Simpletest (1) - Hello World!

  •  
 
kan2019年1月10日 - 17:35 に投稿

はじめに

Drupal8のsimpletestでテストケースをどう書くのかを紹介する日本語の記事が少ないし、最近関わる仕事はDrupal8のテスト関連なので、そこで積もった経験や知識を初心者向けに数回分けて紹介する。

本文は第一弾。

実行環境

本文の実行環境は以下の通り。

  • CentOS7
  • PHP7
  • Drupal8.6.5

Drupal Consoleのインストール

Drupal8をコマンドで操作できるツールDrupal Consoleをインストールする。

# composer require drupal/console:~1.0 \
--prefer-dist \
--optimize-autoloader

# drupal list
Drupal Console Launcher version 1.3.2
Drupal Console version 1.8.0

Usage:
  command [options] [arguments]

Options:

Available commands:
以下は省略

Simpletestモジュールのインストール

SimpletestモジュールはすでにDrupal8のcoreに入っているが、デフォルトでインストールされていないため、以下のコマンドでインストールする。

# drupal module:install simpletest
 Installing module(s) "simpletest"

 [OK] The following module(s) were installed successfully: "simpletest"                                                 

 // cache:rebuild

 Rebuilding cache(s), wait a moment please.

 [OK] Done clearing cache(s). 

Sampleモジュールの作成

テスト対象となるSampleモジュールの作成手順を以下に示す。

コマンドでSampleモジュールの雛形を自動生成

# drupal generate:module

 // Welcome to the Drupal module generator

 Enter the new module name:
 > Sample

 Enter the module machine name [sample]:
 >

 Enter the module Path [modules/custom]:
 > modules

 Enter module description [My Awesome Module]:
 > Sample

 Enter package name [Custom]:
 > Sample

 Enter Drupal Core version [8.x]:
 > 

 Do you want to generate a .module file? (yes/no) [yes]:
 > 

 Define module as feature (yes/no) [no]:
 > 

 Do you want to add a composer.json file to your module? (yes/no) [yes]:
 > no

 Would you like to add module dependencies? (yes/no) [no]:
 > 

 Do you want to generate a unit test class? (yes/no) [yes]:
 > no

 Do you want to generate a themeable template? (yes/no) [yes]:
 > no

 Do you want proceed with the operation? (yes/no) [yes]:
 >

Generated or updated files
 Generation path: /opt/drupal_simpletest/drupal-8.6.5
 1 - /modules/sample/sample.info.yml
 2 - /modules/sample/sample.module

 Generated lines: "29"

モジュールsampleの有効化

# drupal module:install sample
 Installing module(s) "sample"

 [OK] The following module(s) were installed successfully: "sample"                                                     

 // cache:rebuild

 Rebuilding cache(s), wait a moment please.

 [OK] Done clearing cache(s).        

Hello Worldページの作成

# drupal generate:controller

 // Welcome to the Drupal Controller generator
 Enter the module name [sample]:
 > sample

 Enter the Controller class name [DefaultController]:
 >

 Enter the Controller method title (to stop adding more methods, leave this empty) []:
 > HelloWorld

 Enter the action method name [hello]:
 > helloWorld

 Enter the route path [/sample/helloWorld]:
 > 

 Enter the Controller method title (to stop adding more methods, leave this empty) []:
 > 

 Do you want to generate a unit test class? (yes/no) [yes]:
 > 

 Do you want to load services from the container? (yes/no) [no]:
 > 

 Do you want proceed with the operation? (yes/no) [yes]:
 > 

 // router:rebuild

 Rebuilding routes, wait a moment please

 [OK] Done rebuilding route(s).                                                                                                                                                                             

Generated or updated files
 Generation path: /opt/drupal_simpletest/drupal-8.6.5
 1 - modules/sample/src/Controller/DefaultController.php
 2 - modules/sample/sample.routing.yml
 3 - /DefaultControllerTest.php

 Generated lines: "72"

HelloWorldページの出力内容の変更

ファイルsrc/Controller/DefaultController.phpのソースを以下のように変更。

public function helloWorld() {
  return [
    '#type' => 'markup',
    '#markup' => $this->t('Hello world!')
  ];
}

HelloWorldページの出力内容の確認

URL http://localhost/sample/helloWorld にて"Hello world!"が出力されることを確認する。

テストケースの作成

以下のコマンドでテストクラスファイルを作成する。

# mkdir -p modules/sample/tests/src/Functional/Controller
# touch modules/sample/tests/src/Functional/Controller/DefaultControllerTest.php

ファイルDefaultControllerTest.phpの内容は以下の通り。

<?php

namespace Drupal\Tests\sample\Functional\Controller;

use Drupal\Tests\BrowserTestBase;

/**
 * Test DefaultController
 * 
 * @group sample
 */
class DefaultControllerTest extends BrowserTestBase {

  public static $modules = ['sample'];

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

    $web_user = $this->drupalCreateUser(['access content']);
    $this->drupalLogin($web_user);
  }

  public function testHelloWorld() {
    $this->drupalGet('/sample/helloWorld');
    $this->assertResponse(200);
    $this->assertText('Hello world!');
  }
}

テストケースの実行

phpunitのアップグレード

Drupal8に含まれるphpunitのバージョンが低いため、最新のバージョンにアップグレードする必要がある。

# cd modules/sample/
# php ../../core/scripts/run-tests.sh --non-html --verbose --url http://localhost --class 'Drupal\Tests\sample\Functional\DefaultControllerTest'
  ERROR: PHPUnit testing framework version 6 or greater is required when running on PHP 7.0 or greater. Run the command 'composer run-script drupal-phpunit-upgrade' in order to fix this.

# cd ../../
# composer run-script drupal-phpunit-upgrade
出力省略
# vendor/bin/phpunit --version
PHPUnit 6.5.13 by Sebastian Bergmann and contributors.

実行

以下のコマンドでテストケースDefaultControllerTestを実行して、結果を確認できる。

# php ../../core/scripts/run-tests.sh --non-html --verbose --url http://localhost --class 'Drupal\Tests\sample\Functional\Controller\DefaultControllerTest'

Drupal test run
---------------

Tests to be run:
  - Drupal\Tests\sample\Functional\Controller\DefaultControllerTest

Test run started:
  Wednesday, January 16, 2019 - 12:07

Test summary
------------

Drupal\Tests\sample\Functional\Controller\DefaultControllerT   1 passes                                      

Test run duration: 19 sec

Detailed test results
---------------------


---- Drupal\Tests\sample\Functional\Controller\DefaultControllerTest ----


Status    Group      Filename          Line Function                            
--------------------------------------------------------------------------------
Pass      Other      DefaultController   23 Drupal\Tests\sample\Functional\Cont

参考資料

コメントを追加

プレーンテキスト

  • HTMLタグは利用できません。
  • 行と段落は自動的に折り返されます。
  • ウェブページのアドレスとメールアドレスは自動的にリンクに変換されます。
CAPTCHA
この質問はあなたが人間の訪問者であるかどうかをテストし、自動化されたスパム送信を防ぐためのものです。