1

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);
    }
}
3
  • which version of laravel do you use? Commented Feb 22, 2022 at 18:22
  • 8 but I found the mistake thank you for your time! Commented Feb 23, 2022 at 10:12
  • @Joha Do not replace the original question with the answer as we will never know what the real issue was. You can edit the question and add the answer Commented Feb 23, 2022 at 14:19

1 Answer 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);

    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone! I found the mistake! Seems like the problem was with laravel itself, I delete the composer file and install it again and updated it. Now works fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.