Build your first Laravel package · Part 3 of 4
Testing without an app
Orchestra Testbench boots a bare Laravel just for your tests. Eight tests cover defaults, types, forgetting and the cache; then Pint and PHPStan catch what tests do not.
By Abhishek Fouzdar · Updated
The package works when you poke it from a route. That is not the same as knowing it still works after the next change. This part adds tests, and the interesting problem is that a package has no application to run them in. Orchestra Testbench solves that: it boots a bare Laravel just for the test run. Then two more tools, Pint and PHPStan, catch what tests do not.
Testbench: a Laravel to test inside
In the package folder:
composer require --dev "orchestra/testbench:^10.0|^11.0" "phpunit/phpunit:^11.5|^12.0"
Testbench 10 pairs with Laravel 12 and Testbench 11 with Laravel 13, so the constraint mirrors the one on illuminate/* and Composer picks whichever matches the Laravel it resolved. The --dev matters: people who install your package should not download your test tools. Composer keeps dev dependencies in a separate list and skips them for installs that use --no-dev, which is how production deploys run.
Add a test namespace to composer.json so PHPUnit can find the test classes:
"autoload-dev": {
"psr-4": {
"Shipbytes\\Settings\\Tests\\": "tests/"
}
}
Same shape as the PSR-4 line from part 1, but autoload-dev only applies on your machine and in CI, never in an app that installs the package.
phpunit.xml
Create phpunit.xml in the package root:
<?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="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache">
<testsuites>
<testsuite name="Package">
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
<php>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="CACHE_STORE" value="array"/>
</php>
</phpunit>
The <php> block is the part specific to a package. Testbench's bare Laravel reads these as if they were in a .env: an SQLite database that lives in memory, created fresh for every test and gone when it ends, and the array cache driver, which is a plain PHP array that also vanishes between tests. No database server, no cache server, nothing to clean up. Add .phpunit.cache/ to your .gitignore.
The base test case
Create tests/TestCase.php:
<?php
namespace Shipbytes\Settings\Tests;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Orchestra\Testbench\TestCase as Orchestra;
use Shipbytes\Settings\SettingsServiceProvider;
abstract class TestCase extends Orchestra
{
use RefreshDatabase;
protected function getPackageProviders($app): array
{
return [SettingsServiceProvider::class];
}
}
getPackageProviders is the Testbench equivalent of auto-discovery: the bare app knows nothing about your package until this method names the provider. RefreshDatabase runs the migrations before each test, and because the provider calls loadMigrationsFrom, the package's own migration is among them. That line is the first real test of part 2's wiring: if loadMigrationsFrom were wrong, every test below would fail with "no such table".
The tests
Create tests/SettingsTest.php. Start with the simplest behaviour and build up:
<?php
namespace Shipbytes\Settings\Tests;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Shipbytes\Settings\Facades\Settings;
use Shipbytes\Settings\Models\Setting;
class SettingsTest extends TestCase
{
public function test_a_setting_that_was_never_set_returns_the_default(): void
{
$this->assertNull(Settings::get('site_name'));
$this->assertSame('Acme', Settings::get('site_name', 'Acme'));
$this->assertFalse(Settings::has('site_name'));
}
public function test_a_setting_can_be_set_and_read_back(): void
{
Settings::set('site_name', 'Acme');
$this->assertSame('Acme', Settings::get('site_name'));
$this->assertTrue(Settings::has('site_name'));
$this->assertDatabaseHas('settings', ['key' => 'site_name']);
}
public function test_setting_the_same_key_again_updates_the_row(): void
{
Settings::set('site_name', 'Acme');
Settings::set('site_name', 'Acme Ltd');
$this->assertSame('Acme Ltd', Settings::get('site_name'));
$this->assertSame(1, Setting::query()->count());
}
public function test_values_keep_their_type(): void
{
Settings::set('registration_open', false);
Settings::set('max_uploads', 25);
Settings::set('allowed_domains', ['acme.test', 'example.test']);
$this->assertFalse(Settings::get('registration_open'));
$this->assertSame(25, Settings::get('max_uploads'));
$this->assertSame(['acme.test', 'example.test'], Settings::get('allowed_domains'));
}
public function test_a_setting_can_be_forgotten(): void
{
Settings::set('site_name', 'Acme');
Settings::forget('site_name');
$this->assertFalse(Settings::has('site_name'));
$this->assertSame('fallback', Settings::get('site_name', 'fallback'));
}
}
Each test name is a sentence, and each test checks one sentence. test_values_keep_their_type is the one that would have caught the string-"false" bug from part 2; assertSame fails when the types differ, where assertEquals would let "25" pass for 25.
For how the same ideas apply inside an application rather than a package, with a real database, queues, mail and a browser, see Laravel feature and unit tests, with a real app.
Now the two tests that justify the cache code. They need a trick: the Settings object is a singleton, so within one test it never re-reads anything. To act like a new request, throw the instance away:
public function test_the_table_is_read_once_and_then_served_from_cache(): void
{
Settings::set('site_name', 'Acme');
$this->app->forgetInstance(\Shipbytes\Settings\Settings::class);
DB::enableQueryLog();
Settings::get('site_name');
Settings::get('support_email', '[email protected]');
Settings::get('site_name');
$this->assertCount(1, DB::getQueryLog(), 'Three reads should cost one query.');
$this->assertTrue(Cache::has('shipbytes.settings'));
$this->app->forgetInstance(\Shipbytes\Settings\Settings::class);
DB::flushQueryLog();
Settings::get('site_name');
$this->assertCount(0, DB::getQueryLog());
}
public function test_writing_a_setting_invalidates_the_cache(): void
{
Settings::set('site_name', 'Acme');
Settings::get('site_name');
Settings::set('site_name', 'Acme Ltd');
$this->assertFalse(Cache::has('shipbytes.settings'));
$this->assertSame('Acme Ltd', Settings::get('site_name'));
}
forgetInstance tells the container to drop the singleton, so the next facade call builds a fresh Settings with an empty $loaded. The query log then shows what a new request would cost: one query for three reads, then zero queries for a request after that, because the cache answers. The second test checks the other half of the promise: a write removes the cache entry, and the next read sees the new value.
One last small test pins the config merging from part 1:
public function test_the_config_file_is_merged_with_defaults(): void
{
$this->assertSame('settings', config('settings.table'));
$this->assertSame('shipbytes.settings', config('settings.cache.key'));
}
Run them:
vendor/bin/phpunit
........ 8 / 8 (100%)
Time: 00:00.24, Memory: 36.50 MB
OK (8 tests, 20 assertions)
Well under a second, no servers involved. That is the test suite you will run after every change from now on.
Pint: one style, no arguments
composer require --dev laravel/pint
Create pint.json:
{
"preset": "laravel"
}
vendor/bin/pint rewrites your files to Laravel's own code style; vendor/bin/pint --test only reports, which is what CI will run. Adopting the Laravel preset means a contributor's editor and yours agree without a discussion, and it means your package looks like the framework it plugs into.
PHPStan: the bugs tests do not reach
composer require --dev larastan/larastan
Larastan is PHPStan with knowledge of Laravel: it understands facades, Eloquent and the container, so it does not flag every Settings::get() as a call to a method that does not exist. Create phpstan.neon:
includes:
- vendor/larastan/larastan/extension.neon
parameters:
level: 6
paths:
- src
Level 6 is a reasonable start for a new package: it insists on return types and on type information for arrays, which is why Settings carries @var array<string, mixed> and @return array<string, mixed> docblocks. Run it:
vendor/bin/phpstan analyse
[OK] No errors
If you start at level 6 from the first commit, staying there is free. Turning it on later, on a package that has grown, is a weekend.
Three commands, three scripts
Add to composer.json so nobody has to remember the paths:
"scripts": {
"test": "phpunit",
"lint": "pint --test",
"analyse": "phpstan analyse"
}
Now composer test, composer lint and composer analyse are the whole quality bar, and part 4 teaches a machine to run them.
Checkpoint
You should have:
phpunit.xml,tests/TestCase.php,tests/SettingsTest.php,pint.json,phpstan.neon;composer testprintingOK (8 tests, 20 assertions);composer lintandcomposer analyseboth clean.
The matching commit is Part 3: testing without an app.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
3 / 4