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
Requires
- php: ^8.2|^8.3|^8.4
- illuminate/support: ^10.0|^11.0|^12.0
- nesbot/carbon: ^2.0|^3.0
- nikic/php-parser: ^4.17|^5.0
- symfony/clock: ^6.0|^7.0|^8.0
- symfony/console: ^6.0|^7.0|^8.0
- symfony/finder: ^6.0|^7.0|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- infection/infection: ^0.32.3
- mockery/mockery: ^1.6
- orchestra/testbench: ^8.0|^9.0
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^10.0|^11.0
README
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:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing) - Write tests for your changes
- Ensure all tests pass (
composer test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing) - 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:
- nikic/php-parser - PHP AST parsing
- symfony/console - CLI interface
- symfony/finder - File searching
๐ Star History
If you find this project useful, please consider giving it a star! โญ
๐ Support
- ๐ง Email: berkay@example.com
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
Made with โค๏ธ for the Laravel community