Pest Testing: Actions, Fakes &amp; Arch Assertions | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Clean Architecture Testing with Pest: Actions, Fakes, and Architectural Assertions

 Clean Architecture Testing with Pest: Actions, Fakes, and Architectural Assertions
===================================================================================

 Go beyond feature tests. Learn how to test Laravel actions, enforce architectural rules, and use Pest's expectation API to keep a clean-architecture codebase honest without drowning in mocks.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 7 Jul 2026 · Updated 7 Jul 2026 · 3 min read

ShareCopy linkCopied

 ![Clean Architecture Testing with Pest: Actions, Fakes, and Architectural Assertions](https://cdn.msaied.com/388/fc5d6303a4c8676ae736106bdc4bfcce.png) 

  On this page +1. [Why Clean Architecture and Pest Are a Natural Pair](#why-clean-architecture-and-pest-are-a-natural-pair)
2. [Testing Actions in Isolation](#testing-actions-in-isolation)
3. [Fake Collaborators via the Service Container](#fake-collaborators-via-the-service-container)
4. [Enforcing Boundaries with arch()](#enforcing-boundaries-with-codearchcode)
5. [Combining Expectations for Richer Assertions](#combining-expectations-for-richer-assertions)
6. [Takeaways](#takeaways)

 Why Clean Architecture and Pest Are a Natural Pair
--------------------------------------------------

Clean architecture splits your Laravel app into layers — domain actions, DTOs, repositories — but without test discipline those layers collapse back into fat controllers within months. Pest's fluent API, `arch()` plugin, and first-class fake support give you three distinct levers to keep boundaries honest: **unit-level action tests**, **fake collaborators that replace the service container**, and **static architectural assertions** that run in CI.

---

Testing Actions in Isolation
----------------------------

An action is a single-responsibility class. Test it without booting the framework.

```php
// app/Actions/RegisterUser.php
final class RegisterUser
{
    public function __construct(
        private readonly UserRepository $users,
        private readonly Hasher $hasher,
    ) {}

    public function handle(RegisterUserData $data): User
    {
        $hashed = $this->hasher->make($data->password);
        return $this->users->create($data->email, $hashed);
    }
}

```

```php
// tests/Unit/Actions/RegisterUserTest.php
use App\Actions\RegisterUser;
use App\Data\RegisterUserData;

it('hashes the password before persisting', function () {
    $hasher = Mockery::mock(Hasher::class);
    $hasher->expects('make')->with('secret')->andReturn('hashed');

    $repo = Mockery::mock(UserRepository::class);
    $repo->expects('create')
         ->with('alice@example.com', 'hashed')
         ->andReturn(new User);

    $action = new RegisterUser($repo, $hasher);
    $action->handle(new RegisterUserData('alice@example.com', 'secret'));
});

```

No `RefreshDatabase`, no HTTP overhead. These tests run in milliseconds.

---

Fake Collaborators via the Service Container
--------------------------------------------

For integration-level tests you still want real Laravel wiring but fake I/O. Bind a fake inside a `beforeEach` rather than scattering `Mail::fake()` calls everywhere.

```php
// tests/Feature/RegisterUserFeatureTest.php
use App\Contracts\UserRepository;
use App\Fakes\InMemoryUserRepository;

beforeEach(function () {
    $this->app->bind(UserRepository::class, InMemoryUserRepository::class);
});

it('stores a new user through the HTTP layer', function () {
    $response = $this->postJson('/register', [
        'email'    => 'bob@example.com',
        'password' => 'password',
    ]);

    $response->assertCreated();

    $repo = $this->app->make(UserRepository::class);
    expect($repo->all())->toHaveCount(1)
        ->and($repo->all()->first()->email)->toBe('bob@example.com');
});

```

`InMemoryUserRepository` implements the same contract as the Eloquent version — no database, no migrations, deterministic.

---

Enforcing Boundaries with `arch()`
----------------------------------

Pest's `arch()` helper turns architectural rules into executable tests. Add these to a dedicated `tests/ArchTest.php`.

```php
arch('domain layer has no framework dependencies')
    ->expect('App\Domain')
    ->toUseNothing()
    ->ignoring('Illuminate\Contracts'); // interfaces are fine

arch('actions are final')
    ->expect('App\Actions')
    ->toBeFinal();

arch('DTOs are readonly')
    ->expect('App\Data')
    ->toBeReadonly();

arch('repositories live behind contracts')
    ->expect('App\Repositories')
    ->toImplement('App\Contracts\Repository');

```

These assertions run statically — no database, no HTTP. They fail the moment a junior dev imports `Illuminate\Http\Request` inside a domain class.

---

Combining Expectations for Richer Assertions
--------------------------------------------

Pest's expectation API chains cleanly with custom higher-order helpers.

```php
expect(RegisterUserData::class)
    ->toBeReadonly()
    ->and(RegisterUserData::class)
    ->toHaveConstructor()
    ->and(new RegisterUserData('a@b.com', 'pw'))
    ->email->toBe('a@b.com');

```

This single chain verifies the DTO is immutable, constructable, and maps properties correctly — three concerns, one readable block.

---

Takeaways
---------

- **Test actions directly** with constructor injection; skip the framework bootstrap for pure domain logic.
- **Bind in-memory fakes** in `beforeEach` rather than using static facade fakes — your tests stay container-aware without coupling to concrete implementations.
- **`arch()` assertions are free CI guards** — they catch boundary violations before code review.
- **Readonly DTOs + final actions** are enforceable conventions, not just style guidelines, when you back them with Pest.
- Keep a single `ArchTest.php` as the living documentation of your architectural rules.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [pest](https://www.msaied.com/public/articles?search=pest)
- [testing](https://www.msaied.com/public/articles?search=testing)
- [clean-architecture](https://www.msaied.com/public/articles?search=clean-architecture)

 Frequently asked questions 
---------------------------

  Does arch() perform runtime analysis or static analysis?Pest's arch() uses static reflection — it inspects class metadata without executing code. This makes it fast and safe to run in CI without a database or running application.

   When should I use an InMemoryRepository fake versus RefreshDatabase?Use an in-memory fake when testing application logic that flows through a repository contract. Use RefreshDatabase when you specifically need to verify SQL queries, migrations, or Eloquent behaviour itself.

   Can arch() assertions check for prohibited imports across namespaces?Yes. Use -&gt;toUseNothing() or -&gt;toUseStrictly(\['AllowedNamespace'\]) to whitelist exactly which dependencies a namespace may import, catching accidental cross-layer coupling automatically.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleMulti-Tenant SaaS with Laravel + Filament: Scoped Queues, Notifications, and Storage per Tenant](https://www.msaied.com/public/articles/multi-tenant-saas-with-laravel-filament-scoped-queues-notifications-and-storage-per-tenant) [Next articleMulti-Tenant SaaS with Laravel: Isolating Queues, Storage, and Notifications Per Tenant](https://www.msaied.com/public/articles/multi-tenant-saas-with-laravel-isolating-queues-storage-and-notifications-per-tenant)  

   On this page
-------------

1. [Why Clean Architecture and Pest Are a Natural Pair](#why-clean-architecture-and-pest-are-a-natural-pair)
2. [Testing Actions in Isolation](#testing-actions-in-isolation)
3. [Fake Collaborators via the Service Container](#fake-collaborators-via-the-service-container)
4. [Enforcing Boundaries with arch()](#enforcing-boundaries-with-codearchcode)
5. [Combining Expectations for Richer Assertions](#combining-expectations-for-richer-assertions)
6. [Takeaways](#takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
