Skip to content

PHP unit testing

Unit tests run small parts of your game's PHP code locally, without opening a Studio table. They are particularly useful for legal moves, scoring, and special rules: give the code a known position and check the result.

Start with rules that take ordinary PHP values and return a result. These tests do not need the BGA framework or a database. Keep testing the complete game in Studio as well, to check database changes, state transitions, notifications, and the interface.

Install PHPUnit in your game project

You need Composer and PHP on the command line. These examples use PHPUnit 13, which requires PHP 8.4 or later installed on your computer (use php --version to check).

Run this command from your game's root directory:

composer require --dev phpunit/phpunit:^13

This installs PHPUnit in the project's vendor/ directory.

Add these entries to your game's .gitignore:

/vendor/
/.phpunit.cache/

Commit composer.json and composer.lock, together with your tests and their configuration. Another developer can then run composer install to get the same dependency versions.

In .vscode/sftp.json, add vendor and .* to the existing ignore array if they are not already excluded.

Configure the test runner

Merge this entry into your composer.json, alongside the require-dev entry created by Composer:

"autoload": {
    "psr-4": {
        "Bga\\Games\\MyGame\\": "modules/php/"
    }
}

Replace MyGame with your game's PHP namespace. Regenerate the autoloader after editing the file:

composer dump-autoload

Create phpunit.xml.dist in the game root:

phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="tests/bootstrap.php"
         colors="true"
         cacheDirectory=".phpunit.cache"
         failOnWarning="true"
         failOnRisky="true">
    <testsuites>
        <testsuite name="Game">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

The test runner automatically finds this configuration. Composer loads your game classes from modules/php/. The bootstrap below also loads the small framework substitute used by the example.

Example: test the Reversi board manager

Use the Board\BoardManager and Board\Disc classes from the current Reversi tutorial.

The tutorial uses a Collection<Disc> keyed by disc ID. We will supply fixed discs instead of loading them through ItemManager, and skip the board manager's constructor so it does not initialize framework services.

Provide the collection methods used by the rules

Create this small test substitute for the framework's Collection. It implements only the operations used here, including returning new collections from add() and merge() and preserving disc IDs. It does not implement ItemManager or database access.

tests/stubs/BgaFrameworkStubs.php
<?php

declare(strict_types=1);

namespace Bga\GameFramework\Helpers;

class Collection extends \ArrayObject
{
    public function find(callable $fn): mixed
    {
        foreach ($this as $key => $value) {
            if ($fn($value, $key)) {
                return $value;
            }
        }

        return null;
    }

    public function add(mixed $obj, ?int $id = null): Collection
    {
        $items = $this->getArrayCopy();
        $items[$id ?? $obj->id] = $obj;

        return new Collection($items);
    }

    public function merge(Collection $arr): Collection
    {
        return new Collection($this->getArrayCopy() + $arr->getArrayCopy());
    }

    public function isEmpty(): bool
    {
        return $this->count() === 0;
    }

    public function values(): array
    {
        return array_values($this->getArrayCopy());
    }
}

Load it before the game classes:

tests/bootstrap.php
<?php

declare(strict_types=1);

require_once __DIR__ . '/stubs/BgaFrameworkStubs.php';
require_once __DIR__ . '/../vendor/autoload.php';

The Disc class's ItemManager attributes do not need substitutes for these tests: creating an ordinary Disc does not instantiate its attributes. The tests also do not construct Game or call any ItemManager methods.

Create the tests

Replace MyGame in the imports with the same namespace you configured in composer.json.

tests/BoardManagerTest.php
<?php

declare(strict_types=1);

namespace Tests;

use Bga\GameFramework\Helpers\Collection;
use Bga\Games\MyGame\Board\BoardManager;
use Bga\Games\MyGame\Board\Disc;
use PHPUnit\Framework\TestCase;

final class BoardManagerTest extends TestCase
{
    /**
     * Checks that one move captures discs in several directions,
     * preserving the captured disc objects and their IDs.
     */
    public function testCapturesInSeveralDirections(): void
    {
        $board = $this->createBoard([
            [2, 2, 1], [2, 4, 1], [3, 3, 2],
            [3, 4, 2], [4, 5, 2], [4, 6, 1],
        ]);
        $manager = $this->createBoardManager($board);

        $flipped = $manager->getFlippedDiscs(4, 4, 1, $board);

        self::assertCount(3, $flipped);
        self::assertSame($board[3], $flipped[3]);
        self::assertSame($board[4], $flipped[4]);
        self::assertSame($board[5], $flipped[5]);
    }

    /**
     * Checks that opposing discs reaching the board edge are not captured
     * unless a disc of the playing side closes the line.
     */
    public function testDoesNotCaptureAnUnclosedLineAtTheEdge(): void
    {
        $board = $this->createBoard([[1, 1, 2], [2, 1, 2]]);
        $manager = $this->createBoardManager($board);

        self::assertTrue($manager->getFlippedDiscs(3, 1, 1, $board)->isEmpty());
    }

    /**
     * Checks that playing on an occupied cell returns no discs to flip,
     * even when an adjacent line would otherwise be captured.
     */
    public function testCannotPlayOnAnOccupiedCell(): void
    {
        $board = $this->createBoard([[2, 4, 1], [3, 4, 2], [4, 4, 2]]);
        $manager = $this->createBoardManager($board);

        self::assertTrue($manager->getFlippedDiscs(4, 4, 1, $board)->isEmpty());
    }

    /**
     * Checks that side 1 has exactly the four expected legal moves
     * from the initial four-disc position.
     */
    public function testPossibleMovesOnTheInitialBoard(): void
    {
        $board = $this->createBoard([
            [4, 4, 1], [5, 5, 1], [4, 5, 2], [5, 4, 2],
        ]);
        $manager = $this->createBoardManager($board);

        self::assertSame([
            ['x' => 3, 'y' => 5],
            ['x' => 4, 'y' => 6],
            ['x' => 5, 'y' => 3],
            ['x' => 6, 'y' => 4],
        ], $manager->getPossibleMoves(1));
    }

    /** @param list<array{int, int, int}> $positions Each entry is [x, y, side]. */
    private function createBoard(array $positions): Collection
    {
        $discs = [];
        foreach ($positions as $index => [$x, $y, $side]) {
            $disc = new Disc();
            $disc->id = $index + 1;
            $disc->location = 'board';
            $disc->order = $index;
            $disc->x = $x;
            $disc->y = $y;
            $disc->side = $side;
            $discs[$disc->id] = $disc;
        }

        return new Collection($discs);
    }

    private function createBoardManager(Collection $board): BoardManager
    {
        return new class ($board) extends BoardManager {
            public function __construct(private Collection $board)
            {
                // Skip framework initialization; these calculations only need the board.
            }

            public function getBoardDiscs(): Collection
            {
                return $this->board;
            }
        };
    }
}

The test subclass replaces only construction and board loading. Both calculation methods come from the tutorial's production BoardManager. The capture test checks that the returned collection preserves the original disc objects and their IDs; the possible-moves test exercises both calculation methods together.

Run all tests, one file, or one test method:

vendor/bin/phpunit
vendor/bin/phpunit tests/BoardManagerTest.php
vendor/bin/phpunit --filter testCapturesInSeveralDirections

All four tests should pass. Try changing an expected coordinate to see a failure, then restore it.

Optional: run PHP tests through npm

If your game already uses npm for its front-end tools, add this command to the existing scripts object in package.json:

"test:php": "vendor/bin/phpunit"

You can then run the PHP tests through npm, including a single file or method:

npm run test:php
npm run test:php -- tests/BoardManagerTest.php
npm run test:php -- --filter testCapturesInSeveralDirections

This is a shortcut for the same PHPUnit commands above; npm is not required to run PHP tests. If you also follow the front-end unit testing guide, use npm run test:frontend for those tests.

Other code that depends on the framework

Use the same approach for existing code when you can replace data loading with a fixed position. Keep move and scoring methods unchanged. If you skip a constructor, initialize every property the tested calculation uses.

When loading a class that extends a framework class, PHP also needs a declaration for its parent. Add only the declarations your tests require, with compatible method signatures. Make unsupported framework operations throw rather than return plausible empty results. Keep substitutes small; avoid implementing a replacement database or state machine.

Use PHPUnit's createStub() when a dependency only needs to return known values. Use a mock when the interaction itself matters, such as checking that a state gives extra time to the correct player. These doubles normally skip the dependency's constructor, so explicitly configure the methods the tested code calls. They still require the class and its parent declarations to load.

What to test next

Add a test whenever you fix a rule bug: reproduce the position, check that the test fails before the fix, and keep it after fixing the code. Useful cases include an empty selection, a board edge, tied scores, a forced pass, and a game that ends while spaces remain.

If you came here from a tutorial, return to it:

Back to the Reversi tutorial Back to the Hearts tutorial