LaraUtilX Test Suite

This directory contains comprehensive unit and feature tests for the LaraUtilX package.

Test Structure

tests/
├── TestCase.php                    # Base test case with Laravel setup
├── Unit/                          # Unit tests for individual components
│   ├── Enums/
│   │   └── LogLevelTest.php
│   ├── Rules/
│   │   └── RejectCommonPasswordsTest.php
│   ├── Traits/
│   │   ├── ApiResponseTraitTest.php
│   │   └── FileProcessingTraitTest.php
│   └── Utilities/
│       ├── CachingUtilTest.php
│       ├── ConfigUtilTest.php
│       ├── FeatureToggleUtilTest.php
│       ├── FilteringUtilTest.php
│       ├── LoggingUtilTest.php
│       ├── PaginationUtilTest.php
│       ├── QueryParameterUtilTest.php
│       ├── RateLimiterUtilTest.php
│       └── SchedulerUtilTest.php
└── Feature/                       # Integration tests
    ├── Traits/
    │   └── ApiResponseTraitFeatureTest.php
    └── Utilities/
        └── CachingUtilFeatureTest.php

Running Tests

Prerequisites

Make sure you have installed the development dependencies:

composer install --dev

Run All Tests

./vendor/bin/phpunit

Run Specific Test Suites

# Run only unit tests
./vendor/bin/phpunit --testsuite Unit

# Run only feature tests
./vendor/bin/phpunit --testsuite Feature

Run Specific Test Classes

# Run tests for a specific utility
./vendor/bin/phpunit tests/Unit/Utilities/CachingUtilTest.php

# Run tests for a specific trait
./vendor/bin/phpunit tests/Unit/Traits/ApiResponseTraitTest.php

Run Tests with Coverage

./vendor/bin/phpunit --coverage-html coverage

Test Coverage

The test suite provides comprehensive coverage for:

  • Utilities: All utility classes with their methods and edge cases
  • Traits: All traits with their functionality and integration
  • Enums: All enum values and behaviors
  • Rules: Validation rules with various input scenarios
  • Feature Tests: Integration scenarios and performance tests

Test Categories

Unit Tests

  • Test individual components in isolation
  • Mock external dependencies
  • Focus on specific functionality
  • Fast execution

Feature Tests

  • Test component integration
  • Use real Laravel services where appropriate
  • Test end-to-end workflows
  • Performance and scalability tests

Writing New Tests

When adding new functionality to LaraUtilX, follow these guidelines:

  1. Create unit tests for individual methods and classes
  2. Create feature tests for integration scenarios
  3. Use descriptive test names that explain what is being tested
  4. Follow the AAA pattern: Arrange, Act, Assert
  5. Mock external dependencies in unit tests
  6. Test edge cases and error conditions
  7. Maintain high test coverage (aim for 90%+)

Test Data

  • Use factories for creating test data
  • Use realistic data structures
  • Test with both valid and invalid inputs
  • Include edge cases and boundary conditions

Continuous Integration

The test suite is designed to run in CI environments with:

  • SQLite in-memory database
  • Array cache driver
  • Sync queue driver
  • Minimal external dependencies

Test Examples

Unit Test Example

<?php

namespace LaraUtilX\Tests\Unit\Utilities;

use LaraUtilX\Tests\TestCase;
use LaraUtilX\Utilities\ConfigUtil;
use Illuminate\Support\Facades\Storage;

class ConfigUtilTest extends TestCase
{
    private ConfigUtil $configUtil;

    protected function setUp(): void
    {
        parent::setUp();
        $this->configUtil = new ConfigUtil();
    }

    public function test_can_get_all_app_settings()
    {
        $settings = $this->configUtil->getAllAppSettings();

        $this->assertIsArray($settings);
        $this->assertArrayHasKey('name', $settings);
        $this->assertArrayHasKey('env', $settings);
    }

    public function test_can_get_setting_from_existing_file()
    {
        // Create a test settings file
        $testSettings = ['test_key' => 'test_value', 'another_key' => 'another_value'];
        $filePath = 'test_settings.json';

        Storage::put($filePath, json_encode($testSettings));

        $settings = $this->configUtil->getAllSettings($filePath);

        $this->assertEquals($testSettings, $settings);

        // Clean up
        Storage::delete($filePath);
    }

    public function test_returns_empty_array_for_non_existent_file()
    {
        $settings = $this->configUtil->getAllSettings('non_existent_file.json');

        $this->assertEquals([], $settings);
    }
}

Feature Test Example

<?php

namespace LaraUtilX\Tests\Feature\Traits;

use LaraUtilX\Tests\TestCase;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Config;

class ApiResponseTraitFeatureTest extends TestCase
{
    use \LaraUtilX\Traits\ApiResponseTrait;

    public function test_success_response_integration()
    {
        $data = [
            'users' => [
                ['id' => 1, 'name' => 'John Doe'],
                ['id' => 2, 'name' => 'Jane Smith'],
            ],
        ];
        $message = 'Users retrieved successfully';
        $meta = [
            'total' => 2,
            'page' => 1,
        ];

        $response = $this->successResponse($data, $message, 200, $meta);

        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertEquals(200, $response->getStatusCode());

        $responseData = $response->getData(true);
        $this->assertTrue($responseData['success']);
        $this->assertEquals($message, $responseData['message']);
        $this->assertEquals($data, $responseData['data']);
        $this->assertEquals($meta, $responseData['meta']);
    }

    public function test_paginated_response_integration()
    {
        // Create a mock paginator with realistic data
        $items = collect(range(1, 25))->map(function ($i) {
            return [
                'id' => $i,
                'name' => "Item {$i}",
                'created_at' => now()->subDays($i)->toDateTimeString(),
            ];
        });

        $paginator = new LengthAwarePaginator(
            $items->forPage(1, 10),
            25,
            10,
            1,
            ['path' => '/api/items']
        );

        $response = $this->paginatedResponse($paginator, 'Items retrieved successfully');

        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertEquals(200, $response->getStatusCode());

        $responseData = $response->getData(true);
        $this->assertTrue($responseData['success']);
        $this->assertEquals('Items retrieved successfully', $responseData['message']);
        $this->assertCount(10, $responseData['data']);
        $this->assertArrayHasKey('pagination', $responseData['meta']);
    }
}

Best Practices

Test Organization

  • Group related tests in the same class
  • Use descriptive test method names
  • Keep tests focused on a single behavior
  • Use data providers for testing multiple scenarios

Assertions

  • Use specific assertions over generic ones
  • Test both positive and negative cases
  • Verify side effects and state changes
  • Test error conditions and edge cases

Performance

  • Keep unit tests fast (under 100ms each)
  • Use database transactions for feature tests
  • Clean up after each test
  • Mock expensive operations

Troubleshooting

Common Issues

  1. Database Connection Issues

    • Ensure test database is configured
    • Check database migrations are up to date
    • Verify test environment settings
  2. Cache Issues

    • Clear cache before running tests
    • Use array cache driver for testing
    • Reset cache state between tests
  3. File System Issues

    • Use temporary directories for file tests
    • Clean up test files after execution
    • Mock file system operations when appropriate

Debug Tips

  • Use --verbose flag for detailed output
  • Add dd() or dump() for debugging
  • Check Laravel logs for errors
  • Use --stop-on-failure to debug specific tests

Contributing

When contributing to the test suite:

  1. Follow existing patterns and conventions
  2. Add tests for new features before implementation
  3. Update tests when modifying existing functionality
  4. Ensure all tests pass before submitting PRs
  5. Maintain or improve test coverage

Resources