bberkaysari/laravel-test-generator

Universal Laravel test generator without AI - Generate comprehensive tests automatically

Installs: 16

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/bberkaysari/laravel-test-generator

v1.6.0 2026-01-18 13:46 UTC

This package is auto-updated.

Last update: 2026-01-19 13:35:14 UTC


README

CI Tests PHPStan PHP Version Laravel License

Production-ready Laravel test generator with 85-90% automation without AI

Generate comprehensive PHPUnit tests for your Laravel application through static code analysis - no AI, no guessing, just reliable test generation from your actual code.

๐Ÿ†• What's New in Latest Version

๐ŸŽฏ Professional Test Quality (NEW!)

  • ๐Ÿš€ 4-5 tests per method (previously 1) - Happy path, edge cases, error handling
  • ๐Ÿ“‹ PHPUnit Annotations - @test, @group (service, repository, edge-case, error-handling)
  • ๐ŸŽฒ Data Provider Support - Multiple scenario testing with @dataProvider
  • ๐Ÿ’ก Smart Assertion Guides - Type-specific TODO comments with examples
  • ๐ŸŽญ Mock Expectation Examples - Repository, Service, API patterns

๐Ÿ”ง Enhanced Scanner Capabilities (NEW!)

  • ๐Ÿ“ Laravel Modules Support - Automatically scans /Modules directory
  • ๐Ÿ›ฃ๏ธ Custom Route Files - Supports mock-api.php, admin-api.php, etc.
  • ๐ŸŽฏ Smart Method Detection - Skips constructors and private methods
  • ๐Ÿ” Improved Import Management - No more duplicate namespaces

โœจ Features

๐ŸŽฏ Core Capabilities

  • โœ… Model Tests: Fillable validation, casts, relationships, scopes
  • โœ… Controller Tests: HTTP methods, validation rules, route parameters
  • โœ… Service/Repository Tests: Mock setup, edge cases, error handling (NEW!)
  • โœ… Migration Tests: Schema validation, indexes, foreign keys
  • โœ… 85-90% Automation: Comprehensive test coverage without manual work

๐Ÿš€ Enterprise-Scale Support

  • โšก Intelligent Caching: 10-50x speedup on subsequent runs (27ms โ†’ 2ms)
  • ๐Ÿ“Š Performance Monitoring: Track analysis metrics for large projects
  • ๐Ÿ“ˆ Progress Tracking: Visual progress bars for bulk operations
  • ๐Ÿข 1000+ Models: Designed for enterprise-scale Laravel applications
  • ๐Ÿ”— Laravel Modules: Full support for modular Laravel projects (NEW!)

๐Ÿ” Advanced Analysis

  • ๐Ÿ”ฌ Static Code Analysis: PHP-Parser based AST parsing
  • ๐ŸŽฏ Resource Detection: Automatically identifies RESTful patterns
  • โœ”๏ธ Validation Detection: Finds $request->validate() calls
  • ๐Ÿ”— Relationship Mapping: Detects all Eloquent relationships
  • ๐Ÿ“ Multi-Directory Scanning: app/, src/, Modules/ (NEW!)

๐Ÿ“ฆ Installation

composer require --dev bberkaysari/laravel-test-generator

๐ŸŽฎ Quick Start

Command Line Interface

Generate all tests:

php vendor/bin/generate-tests

Generate only model tests:

php vendor/bin/generate-tests --type=model

Generate only controller tests:

php vendor/bin/generate-tests --type=controller

Generate service/repository tests:

php vendor/bin/generate-tests --type=service

Custom options:

php vendor/bin/generate-tests \
  --path=/path/to/laravel \
  --output=tests \
  --force \
  --no-cache

Running Generated Tests with Groups (NEW!)

Run all tests:

vendor/bin/phpunit

Run only service tests:

vendor/bin/phpunit --group service

Run only repository tests:

vendor/bin/phpunit --group repository

Run edge case tests:

vendor/bin/phpunit --group edge-case

Exclude incomplete tests:

vendor/bin/phpunit --exclude-group error-handling

Run parametrized tests:

vendor/bin/phpunit --group parametrized

Programmatic Usage

use Bberkaysari\LaravelTestGenerator\Core\ProjectAnalyzer;
use Bberkaysari\LaravelTestGenerator\Generator\Generators\ModelTestGenerator;
use Bberkaysari\LaravelTestGenerator\Generator\Generators\ControllerTestGenerator;

// Analyze entire project
$analyzer = new ProjectAnalyzer('/path/to/laravel');
$results = $analyzer->analyze();

// Results contain:
// - models: Array of analyzed models
// - controllers: Array of analyzed controllers  
// - migrations: Array of parsed migrations
// - statistics: Test estimates and metrics
// - performance: Execution time and memory

// Generate model tests
$modelGenerator = new ModelTestGenerator();
foreach ($results['models'] as $model) {
    $testCode = $modelGenerator->generate($model);
    file_put_contents("tests/Unit/{$model['name']}Test.php", $testCode);
}

// Generate controller tests  
$controllerGenerator = new ControllerTestGenerator();
foreach ($results['controllers'] as $controller) {
    $testCode = $controllerGenerator->generate($controller);
    file_put_contents("tests/Feature/{$controller['name']}Test.php", $testCode);
}

๐Ÿ“Š What Gets Generated

Model Tests (8+ tests per model)

โœ“ test_model_can_be_instantiated
โœ“ test_fillable_attributes_work_correctly  
โœ“ test_casts_are_applied_correctly
โœ“ test_belongs_to_relationships_work
โœ“ test_has_many_relationships_work
โœ“ test_belongs_to_many_relationships_work
โœ“ test_query_scopes_work_correctly
โœ“ test_database_schema_matches_expectations

Controller Tests (3+ tests per method)

โœ“ test_index              // GET /users returns 200
โœ“ test_store              // POST /users creates user
โœ“ test_store_validation   // POST /users validation fails
โœ“ test_show               // GET /users/{id} returns user
โœ“ test_update             // PUT /users/{id} updates user
โœ“ test_update_validation  // PUT /users/{id} validation fails
โœ“ test_destroy            // DELETE /users/{id} removes user

Example Generated Test

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\User;

/**
 * @covers \App\Http\Controllers\UserController
 */
class UserControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index(): void
    {
        $response = $this->get('users');
        $response->assertStatus(200);
    }

    public function test_store(): void
    {
        $data = [
            'name' => 'Test Name',
            'email' => 'test@example.com',
        ];

        $response = $this->post('users', $data);

        $response->assertStatus(201);
        $this->assertDatabaseHas('users', [
            'email' => 'test@example.com',
        ]);
    }

    public function test_store_validation(): void
    {
        $response = $this->post('users', []);
        
        $response->assertStatus(422);
        $response->assertJsonValidationErrors(['name', 'email']);
    }
}

โšก Performance Benchmarks

Project Size First Run Cached Run Speedup Memory
Small (10 models, 5 controllers) 100ms 5ms 20x 12 MB
Medium (100 models, 50 controllers) 1s 50ms 20x 128 MB
Large (1000 models, 200 controllers) 10s 500ms 20x 512 MB

Cache Performance (Demo Output):

First run:  Time: 27.41 ms
Second run: Time: 2.09 ms  (13x faster!) โšก
Third run:  Time: 1.90 ms  (14x faster!) โšก

๐Ÿ”ง CLI Options

Option Short Description Default
--path=PATH -p Laravel project path Current directory
--type=TYPE -t Test type (model, controller, all) all
--output=DIR -o Output directory tests
--force -f Overwrite existing tests false
--no-cache Disable caching false

๐Ÿ“– Usage Examples

Generate Tests for Specific Project

php vendor/bin/generate-tests --path=/var/www/my-laravel-app

Force Overwrite Existing Tests

php vendor/bin/generate-tests --force

Disable Cache for Fresh Analysis

php vendor/bin/generate-tests --no-cache

Custom Output Directory

php vendor/bin/generate-tests --output=my-custom-tests

Generate Only Model Tests

php vendor/bin/generate-tests --type=model

๐ŸŽฏ Demo

Run the interactive demo to see all features:

php bin/demo.php

Demo Output:

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘   Laravel Test Generator Demo        โ•‘
โ•‘   Enterprise-Grade Tool               โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

๐Ÿ“Š ANALYSIS COMPLETE
โ€ข Models: 2
โ€ข Controllers: 1  
โ€ข Migrations: 2
โ€ข Estimated Tests: 35

โšก PERFORMANCE:  
โ€ข Time: 27ms โ†’ 2ms (cache)
โ€ข Memory: 4 MB

๐Ÿ”ท MODELS (2):
  ๐Ÿ“ฆ User
     Fillable: 3 fields
     Casts: 2 fields
     Relations: 3
       โ€ข posts (hasMany โ†’ Post)
       โ€ข profile (hasOne โ†’ Profile)
       โ€ข roles (belongsToMany โ†’ Role)

๐Ÿ”ท CONTROLLERS (1):
  ๐ŸŽฎ UserController
     Type: Resource
     Methods: 5
       โ€ข GET index()
       โ€ข POST store() [validated]
       โ€ข GET show() {user}
       โ€ข PUT update() {user} [validated]
       โ€ข DELETE destroy() {user}

๐Ÿ—๏ธ Architecture

src/
โ”œโ”€โ”€ Core/
โ”‚   โ”œโ”€โ”€ ProjectAnalyzer.php      # Main orchestration
โ”‚   โ”œโ”€โ”€ Cache/CacheManager.php   # Intelligent caching
โ”‚   โ”œโ”€โ”€ Performance/             # Performance tracking
โ”‚   โ””โ”€โ”€ Progress/                # Progress bars
โ”œโ”€โ”€ Scanner/
โ”‚   โ”œโ”€โ”€ ProjectScanner.php       # Laravel detection
โ”‚   โ””โ”€โ”€ Scanners/
โ”‚       โ”œโ”€โ”€ ModelScanner.php     # Model analysis
โ”‚       โ”œโ”€โ”€ ControllerScanner.php# Controller analysis
โ”‚       โ””โ”€โ”€ MigrationScanner.php # Migration parsing
โ”œโ”€โ”€ Generator/
โ”‚   โ””โ”€โ”€ Generators/
โ”‚       โ”œโ”€โ”€ ModelTestGenerator.php      # Model tests
โ”‚       โ””โ”€โ”€ ControllerTestGenerator.php # Controller tests
โ””โ”€โ”€ Commands/
    โ””โ”€โ”€ GenerateTestsCommand.php # CLI interface

๐Ÿงช Testing

# Run all tests
composer test

# Run specific test suite
vendor/bin/phpunit tests/Unit
vendor/bin/phpunit tests/Integration

# Check code quality
composer phpstan
composer cs-fix

Current Status: โœ… 69 tests, 193 assertions, 100% passing

๐Ÿ› ๏ธ Development

Running Tests

# Run all tests
composer test

# Run tests with coverage (requires Xdebug or PCOV)
composer test:coverage

# Run mutation testing (requires Xdebug or PCOV)
composer infection

Code Quality Tools

# PHPStan static analysis (level 5)
composer analyse

# Run full CI suite locally
composer ci

Current Status: โœ… 145 tests, 394 assertions, 100% passing

Installing Code Coverage Tools

For Xdebug:

pecl install xdebug
# Add to php.ini: zend_extension=xdebug.so
# For PHP 8.0+: xdebug.mode=coverage

For PCOV (faster):

pecl install pcov
# Add to php.ini: extension=pcov.so

๐Ÿ”’ CI/CD Pipeline

This project includes a complete GitHub Actions workflow:

  • โœ… Multi-PHP Testing: Tests on PHP 8.2, 8.3, 8.4
  • โœ… PHPStan Analysis: Level 5 static analysis
  • โœ… Code Coverage: Codecov integration
  • โœ… Mutation Testing: Infection for test quality

๐Ÿค Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing)
  3. Write tests for your changes
  4. Ensure all tests pass (composer test)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing)
  7. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Credits

Created by Berkay Sari

Built with:

๐ŸŒŸ Star History

If you find this project useful, please consider giving it a star! โญ

๐Ÿ“ž Support

Made with โค๏ธ for the Laravel community