PHPackages                             lucasmelocvl/laravel-model-unit-testing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. lucasmelocvl/laravel-model-unit-testing

ActiveLibrary[Testing &amp; Quality](/categories/testing)

lucasmelocvl/laravel-model-unit-testing
=======================================

Artisan command to automatically generate and merge structural unit tests for all Laravel Eloquent models.

v1.0.0(3w ago)00MITPHPPHP ^7.3|^8.0

Since May 19Pushed 3w agoCompare

[ Source](https://github.com/lucasmelocvl/laravel-model-unit-testing)[ Packagist](https://packagist.org/packages/lucasmelocvl/laravel-model-unit-testing)[ RSS](/packages/lucasmelocvl-laravel-model-unit-testing/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

🛡️ Laravel Model Unit Testing
=============================

[](#️-laravel-model-unit-testing)

[![PHP Version Require](https://camo.githubusercontent.com/fdc564317a831dfa84d1591495f98e95594f1ed8cf07108ba278fd299a94d0a3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f6c756361736d656c6f63766c2f6c61726176656c2d6d6f64656c2d756e69742d74657374696e672f706870)](https://packagist.org/packages/lucasmelocvl/laravel-model-unit-testing)[![Laravel](https://camo.githubusercontent.com/971011523170675c42d02d694320076cc7003951579cb30a2253130070cee577/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d253545352e3825374331312e782d726564)](https://laravel.com)[![Latest Version on Packagist](https://camo.githubusercontent.com/34ada21cddbea08a6a939746690bff93d78d414f3a149bdb40c91ee252db8428/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c756361736d656c6f63766c2f6c61726176656c2d6d6f64656c2d756e69742d74657374696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lucasmelocvl/laravel-model-unit-testing)[![Total Downloads](https://camo.githubusercontent.com/4776d74b8940eb636fedca6f8ce8ac2aa47f0ff6e65820b7728db09e6c29907b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c756361736d656c6f63766c2f6c61726176656c2d6d6f64656c2d756e69742d74657374696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/lucasmelocvl/laravel-model-unit-testing)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)

Eloquent models are the absolute bedrock of any Laravel application. They represent your business logic, govern data transformations, and guard database integrity. Yet, **model configurations are prone to silent, devastating drift**:

- A column is renamed in a migration, but the `$fillable` array is never updated.
- A foreign key name changes, silently breaking an Eloquent relationship method.
- A developer forgets to cast an attribute to `boolean` or `integer`, causing runtime type bugs.
- Missing database tables or obsolete definitions linger unnoticed.

Writing individual, boiler-plate unit tests for dozens of models is mind-numbing and instantly becomes stale.

**`laravel-model-unit-testing`** is a premium, zero-maintenance structural testing suite that shields your Eloquent models from schema drift. By dynamically reflecting your models and checking them directly against your active database schema, it detects structural regressions in milliseconds.

---

⚡ The Smart-Merge Advantage
---------------------------

[](#-the-smart-merge-advantage)

Many generators are destructive: they overwrite your test files and wipe out custom test methods you worked hard to build.

Our generator is designed with a **Defensive Smart-Merge Engine**. When you run the generator with the `--force` flag:

1. It parses your existing test file to identify custom test methods and extra PHP `use` imports.
2. It regenerates only the structural expectations (like `expectedTable()`, `expectedFillable()`, `expectedRelationships()`).
3. It safely injects your custom test methods and imports back into the class, completely preserved.

**Your custom tests will never be lost.**

---

✨ Key Features
--------------

[](#-key-features)

- 🔍 **Full Automatic Discovery:** Searches all nested subfolders (`app/Models/**/*.php`) to discover all models recursively.
- 📋 **Configuration Validation:** Automatically asserts exact alignment for `$table`, `$primaryKey`, `$incrementing`, and `$keyType`.
- 🛡️ **Attribute Security:** Asserts the exact lists of `$fillable`, `$guarded`, `$hidden`, and `$appends`.
- 💎 **Database Alignment:** Verifies that all fillable, hidden, and date fields actually exist in the database schema.
- ⚙️ **Cast Verification:** Compares Eloquent casts (e.g. `integer`, `boolean`) against real database column types (e.g. `INT`, `TINYINT`) to spot mismatches.
- 🔗 **Deep Relationship Testing:** Executes all defined relationships (e.g., `BelongsTo`, `HasMany`, `MorphTo`) to verify that the related models load correctly and their foreign keys physically exist in the database!

---

🚀 Installation
--------------

[](#-installation)

You can install the package via Composer (development environment recommended):

```
composer require lucasmelocvl/laravel-model-unit-testing --dev
```

The package leverages Laravel package auto-discovery to register the service provider automatically.

---

📖 Usage
-------

[](#-usage)

### 1. Generate Model Tests Automatically

[](#1-generate-model-tests-automatically)

Run the Artisan command to analyze all models and create or merge structural test suites:

```
php artisan models:generate-unit-tests --force
```

This command will:

1. Discover all Eloquent models in your application.
2. Scan the database to report any structural inconsistencies or missing tables.
3. Automatically scaffold premium unit tests in `tests/Unit/Models/` matching the subfolder structures of your models.

### 2. Run the Unit Tests

[](#2-run-the-unit-tests)

Execute the tests via PHPUnit:

```
vendor/bin/phpunit tests/Unit/Models
```

If memory limits are an issue due to extensive test suites, you can run them with a temporary limit override:

```
php -d memory_limit=-1 vendor/bin/phpunit tests/Unit/Models
```

---

🛠️ How it Works
---------------

[](#️-how-it-works)

Generated tests extend the package's robust `BaseModelTest` abstract class:

```
namespace Tests\Unit\Models;

use App\Models\User;
use Lucasmelocvl\LaravelModelUnitTesting\Abstracts\BaseModelTest;

class UserTest extends BaseModelTest
{
    protected function modelClass(): string
    {
        return \App\Models\User::class;
    }

    protected function expectedTable(): string
    {
        return 'users';
    }

    protected function expectedPrimaryKey(): string
    {
        return 'id';
    }

    protected function expectedIncrementing(): bool
    {
        return true;
    }

    protected function expectedKeyType(): string
    {
        return 'int';
    }

    protected function expectedFillable(): array
    {
        return ['name', 'email', 'password'];
    }

    protected function expectedGuarded(): array
    {
        return [];
    }

    protected function expectedHidden(): array
    {
        return ['password', 'remember_token'];
    }

    protected function expectedCasts(): array
    {
        return ['email_verified_at' => 'datetime'];
    }

    protected function expectedDates(): array
    {
        return ['created_at', 'updated_at'];
    }

    protected function expectedAppends(): array
    {
        return [];
    }

    protected function expectedTraits(): array
    {
        return [
            'Illuminate\Database\Eloquent\SoftDeletes',
        ];
    }

    protected function expectedRelationships(): array
    {
        return [
            'orders' => [
                'type' => 'HasMany',
                'related' => 'App\Models\Order',
                'foreignKey' => 'user_id',
            ],
        ];
    }
}
```

---

🤝 Contributing
--------------

[](#-contributing)

We would love to have you help us improve `laravel-model-unit-testing`! Whether you've found a bug, want to add a feature, or have suggestions for better DB schema mappings, your contributions are highly welcome:

1. **Fork** the repository on GitHub.
2. **Clone** your fork locally.
3. Create a descriptive **feature branch** (`git checkout -b feature/cool-new-assertion`).
4. Write high-quality code and include test cases for new behaviors.
5. **Commit** your changes and push them to your fork.
6. Open a **Pull Request** detailing your changes, the rationale behind them, and how they benefit the community.

Feel free to open an **issue** on GitHub if you encounter bugs or want to share feedback! Let's build the safest and most robust testing ecosystem for Laravel developers together.

---

📄 License
---------

[](#-license)

This package is open-source software licensed under the [MIT License](LICENSE).

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance95

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

21d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8130938?v=4)[Lucas Melo](/maintainers/lucasmelocvl)[@lucasmelocvl](https://github.com/lucasmelocvl)

---

Top Contributors

[![lucasmelocvl](https://avatars.githubusercontent.com/u/8130938?v=4)](https://github.com/lucasmelocvl "lucasmelocvl (3 commits)")

### Embed Badge

![Health badge](/badges/lucasmelocvl-laravel-model-unit-testing/health.svg)

```
[![Health](https://phpackages.com/badges/lucasmelocvl-laravel-model-unit-testing/health.svg)](https://phpackages.com/packages/lucasmelocvl-laravel-model-unit-testing)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.4k](/packages/larastan-larastan)[laravel/ai

The official AI SDK for Laravel.

9782.1M153](/packages/laravel-ai)[spatie/laravel-health

Monitor the health of a Laravel application

87311.3M149](/packages/spatie-laravel-health)[illuminate/queue

The Illuminate Queue package.

20432.2M1.5k](/packages/illuminate-queue)[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
