Moodle Phpunit Testing logo

Moodle Phpunit Testing

Community
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.

Overview

PublisherSaadRahman01
Repositoryclaude-moodle-dev
Skill namemoodle-phpunit-testing
Stars
42
Forks
7
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by SaadRahman01 on GitHub. Read the source before you install it.

Installation

Install the Moodle Phpunit Testing AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-phpunit-testing
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Moodle Phpunit Testing in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Moodle Phpunit Testing on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Moodle Phpunit Testing is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Moodle Phpunit Testing AI skill do?

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.

Why use Moodle Phpunit Testing on TypingMind?

Because you install it once and use it with any model. Moodle Phpunit Testing is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Moodle Phpunit Testing in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-phpunit-testing. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Moodle Phpunit Testing?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Moodle Phpunit Testing?

As many as you like. As long as a model supports skills, you can use Moodle Phpunit Testing with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Moodle Phpunit Testing AI skill free?

Yes. It is published on GitHub by SaadRahman01 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇