I made the following controller:
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use App\Models\Record;
class SpyController extends BaseController
{
public function add(Request $request)
{
$model = new Record();
$model->value = $request->get('value');
return new JsonResponse(['message'=>'Insert Success','record'=>$model],201);
}
}
And I want to test that upon a successful insertion, a value will be inserted:
namespace Tests\Controller;
use Illuminate\Testing\Fluent\AssertableJson;
use Laravel\Sanctum\Sanctum;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\DatabaseTestCase;
class SpyRoutesTest extends TestCase
{
public function addSuccess()
{
DB::fake()
$response = $this->put('/record',['value'=>'lalalala']);
$this->assertStatus(201);
}
}
But in my case, how I can mock the actual Insertion of the record? Will the fake() just assume a successfull insertion? Also, how I can mock an error in the database for example a connection timeout as well?
RefreshDatabase, you database will be wiped either between tests, or when tests are finished (I think it's between, but I don't recall 100%). If you set up a.env.testing, that points at a testing database, you can run all of your tests, insert actual data and not have to worry about mocking anything. Someone else might know how to do this mocking, but it's not something I've ever done.