'Laravel model testing: model->save failed my phpunit testcase

I am starting to write a Unit test using PHPUnit, and I am facing a problem, which I have no idea why. I am testing one of my API endpoints, where I send a request with the data of the animal and save it into the DB;

Currently, I have a model, a controller, and a test class. It works perfectly fine when testing manually, but using the PHPUnit test, it stopped (right at the "save" method to DB). So when I start testing, I get a status code 500 back instead of a 200. Does anyone have an idea how to solve this problem?

AnimalController.php

class AnimalController extends Controller
{
    public function api_antrag_absenden(Request $request)
    {
        $antrag = new Animal();
        $antrag->name = $request->name;
        $antrag->age = $request->age;
        $antrag->save(); // the problem is here

        return response()->json(["saved"], 200);
    }

AnimalTest.php

class AnimaltTest extends TestCase
{
    use DatabaseTransactions;

    public function testPostwithData()
    {
        $response = $this->json('post','api/animal/send',[
            'name ' => 'Frank',
            'year' => 2,
        ]);

        $response->assertStatus(200);
    }
}


Solution 1:[1]

    class AnimaltTest extends TestCase
{
    use DatabaseTransactions;

    public function testPostwithData()
    {
        // you did not use below code so I removed it.
        // $animal = Animal::factory()->make();
        $response = $this->json('post','api/animal/send',[
            'name ' => 'Frank',
            'year' => 2, // you used $request->year so it is not age, you must send year
        ]);

        $response->assertStatus(200);

    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gguney