Moodle Phpunit Testingのロゴ

Moodle Phpunit Testing

コミュニティ
SaadRahman01
moodle-phpunit-testing

Use when writing, running, or debugging PHPUnit tests for Moodle plugins or core. Covers advanced_testcase, resetAfterTest, data generators, mocking $DB, testing events/tasks/external functions, and CLI invocation.

概要

公開者SaadRahman01
リポジトリclaude-moodle-dev
スキル名moodle-phpunit-testing
スター
42
フォーク
7
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    SaadRahman01がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルMoodle Phpunit TestingをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-phpunit-testing
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-phpunit-testing .claude/skills/moodle-phpunit-testing
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでMoodle Phpunit Testingを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にMoodle Phpunit Testingを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Moodle Phpunit Testingは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Moodle PHPUnit Testing

Overview

Moodle ships its own PHPUnit harness with test bootstrap, transactional resets, and data generators. Tests live in <plugin>/tests/<thing>_test.php and extend advanced_testcase. Never call parent::setUp() for DB cleanup — use $this->resetAfterTest().

When to Use

  • Writing unit/integration tests for any Moodle plugin or core API
  • Debugging test failures (Database was modified errors, isolation issues)
  • Adding a data generator (tests/generator/lib.php)
  • Testing events, scheduled tasks, ad-hoc tasks, external functions
  • Setting up CI for Moodle test suites

Skip when: writing Behat acceptance tests (use moodle-behat-testing).

First-time setup

bash
php admin/tool/phpunit/cli/init.php       # writes phpunit.xml + initializes test DB
vendor/bin/phpunit --testsuite local_example_testsuite

phpunit.xml is regenerated by init.php — never hand-edit. Re-run after installing a new plugin.

Test class skeleton

php
<?php
namespace local_example;
defined('MOODLE_INTERNAL') || die();

/**
 * @group local_example
 * @covers \local_example\manager
 */
final class manager_test extends \advanced_testcase {

    public function test_create_item(): void {
        $this->resetAfterTest();
        $generator = self::getDataGenerator();
        $course = $generator->create_course();
        $user = $generator->create_user();

        $manager = new manager();
        $id = $manager->create_item($course->id, $user->id, 'hello');

        global $DB;
        $row = $DB->get_record('local_example_items', ['id' => $id], '*', MUST_EXIST);
        $this->assertSame('hello', $row->name);
    }
}

Key rules:

  • File name: <thing>_test.php, class: <thing>_test
  • final class (Moodle policy since 4.2)
  • @covers annotation required by Moodle CS
  • @group <component> enables --group filtering
  • void return type on test methods, : void on setUp
  • self:: (not $this->) for static methods like getDataGenerator()

Data generators

Plugin generator at tests/generator/lib.php:

php
<?php
defined('MOODLE_INTERNAL') || die();

class local_example_generator extends component_generator_base {
    public function create_item(array $record = []): \stdClass {
        global $DB, $USER;
        $defaults = [
            'courseid'   => 0,
            'userid'     => $USER->id,
            'name'       => 'Item ' . random_string(8),
            'timecreated'=> time(),
        ];
        $record = (object)array_merge($defaults, $record);
        $record->id = $DB->insert_record('local_example_items', $record);
        return $record;
    }
}

Use:

php
$gen = self::getDataGenerator()->get_plugin_generator('local_example');
$item = $gen->create_item(['name' => 'test']);

Activity module generator extends testing_module_generator and implements create_instance().

Common patterns

Test an event

php
$sink = $this->redirectEvents();
$manager->do_thing();
$events = $sink->get_events();
$sink->close();
$this->assertCount(1, $events);
$this->assertInstanceOf(\local_example\event\thing_done::class, $events[0]);

Test an email

php
$sink = $this->redirectEmails();
$manager->notify($user);
$messages = $sink->get_messages();
$this->assertSame($user->email, $messages[0]->to);

Test a scheduled task

php
$task = new \local_example\task\cleanup();
$task->execute();
// assert side effects

Test an external (web service) function

php
$this->setUser($user);
$result = \local_example\external\get_items::execute($courseid);
$result = \core_external\external_api::clean_returnvalue(
    \local_example\external\get_items::execute_returns(),
    $result
);
$this->assertCount(2, $result);

clean_returnvalue is mandatory — catches schema mismatches.

Test an ad-hoc task

php
\core\task\manager::queue_adhoc_task(new \local_example\task\send_report());
$this->runAdhocTasks(\local_example\task\send_report::class);

Login as a user

php
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);             // sets $USER global
$this->setAdminUser();             // shortcut
$this->setGuestUser();

Time-travel

php
$this->mock_clock_with_frozen(1700000000);    // Moodle 4.4+
// or in older versions, manually set timecreated/timemodified

Running tests

bash
# Single suite
vendor/bin/phpunit --testsuite local_example_testsuite

# Single file
vendor/bin/phpunit local/example/tests/manager_test.php

# Single method
vendor/bin/phpunit --filter test_create_item local/example/tests/manager_test.php

# By group
vendor/bin/phpunit --group local_example

# Coverage (requires xdebug or pcov)
vendor/bin/phpunit --coverage-html coverage/ local/example/tests

Test database

  • Separate DB defined in config.php: $CFG->phpunit_prefix = 'phpu_';
  • Reset between tests via transactions — $this->resetAfterTest() enables it
  • Schema drift error: re-run php admin/tool/phpunit/cli/init.php
  • "Database was modified" failure means a test mutated DB without resetAfterTest()

Mocking

Moodle prefers integration tests with the real test DB over mocking $DB. When you must mock:

php
$mockDB = $this->createMock(\moodle_database::class);
$mockDB->method('get_record')->willReturn((object)['id' => 1]);
// inject via DI, never replace global

Avoid replacing the global $DB — breaks isolation.

Common Mistakes

MistakeFix
Forgetting $this->resetAfterTest()Add at start of every DB-touching test
Class not finalAdd final (Moodle 4.2+ policy)
Missing @coversAdd @covers \Fully\Qualified\Class
Hand-editing phpunit.xmlRe-run admin/tool/phpunit/cli/init.php
Using parent::setUp() to reset DBUse resetAfterTest() instead
Skipping clean_returnvalue on external fnAlways wrap external returns to catch schema bugs
$this->getDataGenerator() (instance)Moodle prefers self::getDataGenerator() (static)
Asserting time with time()Use mock_clock_with_frozen or compare with tolerance

CI snippet (GitHub Actions)

yaml
- name: PHPUnit
  run: |
    php admin/tool/phpunit/cli/init.php
    vendor/bin/phpunit --testsuite ${{ matrix.suite }}

References

よくある質問

AIスキル「Moodle Phpunit Testing」では何ができますか?

Use when writing, running, or debugging PHPUnit tests for Moodle plugins or core. Covers advanced_testcase, resetAfterTest, data generators, mocking $DB, testing events/tasks/external functions, and CLI invocation.

TypingMindでMoodle Phpunit Testingを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Moodle Phpunit Testingはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにMoodle Phpunit Testingをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-phpunit-testingを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Moodle Phpunit Testingを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Moodle Phpunit Testingは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもMoodle Phpunit Testingを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Moodle Phpunit Testing」は無料ですか?

はい。SaadRahman01がGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇