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

deanira's avatar

API Testing with PHPUnit

HI! I'm a newbie in testing the laravel API. Right now, I'm testing my test case and here is the code

public function testVerifyPengaduan()
    {
        $bearerToken = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImE3NDUxMTUwLWJkODQtMTFlYy1iMWM5LTAwNTA1NmMwMDAwMSIsImVtYWlsIjoiYWRtaW5AZ21haWwuY29tIiwicm9sZSI6IkFkbWluIiwiZXhwIjoxNjU4NzYwMzMzfQ.9BYxXuYIcwPvDynZopGv0LmvEqJJRNukhCsVFJ0nsAk";

        $result = $this->withHeaders(['Authorization' => $bearerToken, 'Accept' => "application/json"])
            ->json('PUT', 'api/pengaduan/verify/' . Str::random(10))
            ->assertStatus(Response::HTTP_CREATED);
    }

but it's giving me error like

Error: Attempt to assign property "status" on null in .../app/Http/Controllers/PengaduanController.php:1197

here is the error trace in my controller/handler

public function verify(request $request, $id)
  {
    $helper = new AuthHelper();
    $admin = $helper->Admin($request->header('Authorization'));
    if (isset($admin['data']['id'])) {
      $idAdmin = $admin['data']['id'];
      $data = Pengaduan::find($id);
      $data->status = "VERIFIED"; (this is line 1197)
      $data->id_admin = $idAdmin;
      $data->save();

      return response()->json(["message" => "Report is on progress!", "data" => $data, "status_code" => 200], 200);
    } else {
      return $admin;
    }
  }

do you guys know how to work this out?

0 likes
1 reply
Sinnbeck's avatar

This returns null as it cannot find the record in the database

$data = Pengaduan::find($id);

I assume this is the id? Str::random(10)

Use an ID you know exist in the database

Please or to participate in this conversation.