Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FullStackFool's avatar

Laravel JSON API Testing

I'm looking for tips or advice on testing a JSON API. This is an internal api, not for public consuption (if that matters). The below is an example of the current format for a simple users endpoint. This works well, and is fast enough, but I'm wondering if there are better or more comprehensive methods?

    /** @test */
    public function it_can_store_users()
    {
        // Given that you are logged in.
        $this->be($you = factory(User::class)->create());

        // And you have permission to store the resource.
        $you->givePermissionTo(['store users']);

        // And you have data.
        $user = factory(User::class)->make()->getAttributes();

        // When you post the user data.
        $response = $this->post(route('api.users.store'), $user);

        // The response is successful.
        $response->assertSuccessful();

        // The response is data wrapped.
        $response->assertJsonStructure(['data' => []]);

        // The data is present in the response.
        $response->assertJsonFragment($user);

        // The data is present in the database.
        $this->assertDatabaseHas('users', $user);
    }
0 likes
3 replies
bugsysha's avatar

So this user is allowed to create new users?

martinbean's avatar

@fullstackfool I don’t really understand that test. You’re creating a user and then testing that you can create that user via your API? But surely that call should fail if the user’s already been created?

FullStackFool's avatar

The first user is the "current" authed user, given the appropriate permissions. Then an api call is made to store a new resource, which happens to be a user. Maybe a confusing example to give

    /** @test */
    public function it_can_store_users()
    {
        // Given that you are logged in.
        $this->be($you = factory(User::class)->create());

        // And you have permission to store the resource.
        $you->givePermissionTo(['store teams']);

        // And you have data.
        $team = factory(Team::class)->make()->getAttributes();

        // When you post the team data.
        $response = $this->post(route('api.teams.store'), $team);

        // The response is successful.
        $response->assertSuccessful();

        // The response is data wrapped.
        $response->assertJsonStructure(['data' => []]);

        // The data is present in the response.
        $response->assertJsonFragment($team);

        // The data is present in the database.
        $this->assertDatabaseHas('teams', $team);
    }

Please or to participate in this conversation.