Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Api Tester Bundle Laravel Package

deozza/api-tester-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require deozza/philarmony-api-tester-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Deozza\PhilarmonyApiTesterBundle\PhilarmonyApiTesterBundle::class => ['all' => true],
    ];
    
  2. Database Setup

    • Configure a dedicated test database in .env.test (or .env for local testing).
    • Use doctrine/doctrine-fixtures-bundle to load test fixtures:
      composer require orm-fixtures
      
    • Define fixtures in tests/ApplicationFixtures (see Folder Structure).
  3. First Test Case Create a test class in tests/Api (e.g., tests/Api/UserTest.php):

    namespace Tests\Api;
    
    use Deozza\PhilarmonyApiTesterBundle\Test\ApiTestCase;
    
    class UserTest extends ApiTestCase
    {
        public function testGetUsers()
        {
            $response = $this->get('/api/users');
            $this->assertEquals(200, $response->getStatusCode());
        }
    }
    

    Run tests:

    php bin/phpunit
    

Implementation Patterns

Core Workflows

  1. Test Structure

    • Fixtures: Load test data via ApplicationFixtures (e.g., UserFixtures).
      // src/DataFixtures/ORM/UserFixtures.php
      public function load(ObjectManager $manager)
      {
          $user = new User();
          $user->setEmail('test@example.com');
          $manager->persist($user);
          $manager->flush();
      }
      
    • Test Classes: Extend ApiTestCase for API-specific assertions (e.g., status codes, JSON responses).
      $this->assertJson($response->getContent());
      $this->assertArrayHasKey('data', json_decode($response->getContent(), true));
      
  2. Request/Response Testing

    • HTTP Methods: Use get(), post(), put(), delete() with optional payloads:
      $response = $this->postJson('/api/users', ['name' => 'John']);
      $this->assertEquals(201, $response->getStatusCode());
      
    • Authentication: Pass tokens/headers via withServerParameters():
      $this->withServerParameters(['HTTP_Authorization' => 'Bearer token']);
      
  3. Database Isolation

    • The bundle auto-resets the test database after each test. For complex scenarios, use transactions:
      $this->beginTransaction();
      // Test logic
      $this->rollBack();
      
  4. Scenario Testing

    • Chain assertions for multi-step workflows:
      $response = $this->postJson('/api/orders', ['product_id' => 1]);
      $orderId = json_decode($response->getContent(), true)['id'];
      $this->assertDatabaseHas('orders', ['id' => $orderId]);
      

Gotchas and Tips

Pitfalls

  1. Database Reset Timing

    • The bundle resets the database after each test. If a test fails midway, fixtures may not load correctly. Use transactions for atomic operations:
      $this->beginTransaction();
      try {
          // Test logic
          $this->commit();
      } catch (\Exception $e) {
          $this->rollBack();
          throw $e;
      }
      
  2. Fixture Loading Order

    • Fixtures are loaded alphabetically. Explicitly order dependencies in fixture class names (e.g., UserFixtures, OrderFixtures where UserFixtures depends on User).
  3. Environment Configuration

    • Ensure .env.test is used for tests (not .env). Override database settings:
      # .env.test
      DATABASE_URL="sqlite:///%kernel.project_dir%/var/test.db"
      
  4. CORS/Headers in Tests

    • If your API relies on CORS, mock headers in tests:
      $this->withServerParameters([
          'HTTP_ORIGIN' => 'http://example.com',
          'CONTENT_TYPE' => 'application/json',
      ]);
      

Debugging Tips

  • Enable Debug Mode: Add to phpunit.xml:
    <php>
        <env name="APP_ENV" value="test"/>
        <env name="APP_DEBUG" value="1"/>
    </php>
    
  • Log SQL Queries: Use Doctrine’s logging in config/packages/dev/doctrine.yaml:
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  • Dump Responses: Inspect raw responses:
    file_put_contents('debug_response.json', $response->getContent());
    

Extension Points

  1. Custom Assertions Extend ApiTestCase to add reusable assertions:

    protected function assertApiSuccess($response)
    {
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertJson($response->getContent());
    }
    
  2. Mocking Services Use Symfony’s createMock() or MockBuilder for external services:

    $paymentGateway = $this->createMock(PaymentGateway::class);
    $paymentGateway->method('charge')->willReturn(true);
    $this->container->set(PaymentGateway::class, $paymentGateway);
    
  3. Parallel Testing Configure PHPUnit for parallel runs (requires SQLite for isolation):

    <phpunit>
        <extensions>
            <extension class="Parallel\Extension"/>
        </extensions>
    </phpunit>
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views