jeudi 28 janvier 2021

how to test controller failed to save data into database in laravel

I want test my laravel 6 application controller method. One of my controller method is to store data into database. The method code in the controller is like this:

public function store(ContactStoreRequest $request)
    {
        $datas = $request->input();
        $contact = ContactInfo::create($datas);
        if ($contact) {
            return response()->json(['message' => 'success'], 201);
        }
        return response()->json(['message' => 'failed'], 400);
        
    } 

I can test the method by sending a request to the route url like this:

public function test_store_contact_info()
{
    
    $info = factory(ContactInfo::class)->make()->toArray();        
    $response = $this->json('POST', '/api/v1/contact', $info->toArray());
    $response->assertStatus(200);
    $this->assertDatabaseHas('contact_infos', ['email' => $info->email]);
}

Thus I can only test the success stored condition. I want also to test the failed to store data to database( return response()->json(['message' => 'failed'], 400);), How should I do that in the test?

Aucun commentaire:

Enregistrer un commentaire