Search code examples
laraveltestingweb-api-testinglaravel-testing

Laravel - Testing API with data dependencies


I'm working on a Laravel application with authentication. The application also has an API. Now I want to test all the API endpoints of the application. The Problem is, that the some Endpoints Need data in the database to "work" with.

How is it possible to test such an application? Do I have to test the application in the correct order to achieve something like that?

For example:

  1. create user
  2. create new post
  3. edit new post
  4. create new user
  5. comment post of user 1
  6. login with user 1
  7. see comments of post
  8. delete post

Or is it possible to simulate stuff like this so I don't need a specific order?

I saw that Laravel has build in HTTP testing, but I don‘t know how to handle the data dependencies.


Solution

  • You can define Factory for creating your models. https://laravel.com/docs/5.8/database-testing#writing-factories For example in our project we have lot's of Factories. They describe how to create model. enter image description here

    And later in your test code you just call $partner = factory(Partner::class)->create() In order to create model.

        public function testUpdate(): void
    {
        /** @var Partner $partner */
        $partner = factory(Partner::class)->create();
        $name = 'Fake Partner';
        $description = 'Fake Partner Description';
    
        $response = $this->putJson('/partners/' . $partner->uuid, [
            'name' => $name,
            'description' => $description,
        ]);
    }
    

    For making action via user you can user actingAs($user)->get( https://laravel.com/docs/5.2/testing#sessions-and-authentication

    If your user required any other references to others 'Entities' You can create them right in the definition in your user factory.

    $factory->define(User::class, static function (Faker $faker) {
        return [
            'organization_id' => factory(Organization::class),
            'name' => $faker->word,
            'description' => $faker->words(3, true),
        ];
    });