Level 5
Hit the database.
Hello,
I have difficulty testing the grounding of the save method.
CategoriesController@store
public function store(ArticleRequest $request)
{
$input = $request->input();
$data = new Article($input);
$response = DB::transaction(function () use ($data, $input) {
try {
$data->save();
} catch (\Exception $e) {
return response()->json($data->errors(), 422);
}
return response()->json($data, 201);
});
return $response;
}
I would like to test the : `return response()->json($data->errors(), 422);``
Function test
public function testStore()
{
/**
* |-------------------------------------------
* | Success
* |-------------------------------------------
*/
$this->json('POST', '/api/articles', $this->input, $this->headers)
->assertStatus(201);
/**
* |-------------------------------------------
* | Failed
* |-------------------------------------------
*/
$this->json('POST', '/api/articles', [], $this->headers)
->assertStatus(500);
}
It works correctly, by in the coverage it indicates to me that the try catch is not tested.
How to make the save method fail to test try catch ?
I tried to mock the model
$stub = $this->createMock(Illuminate\Database\Eloquent\Model::class);
$stub->method('save')->willReturn(true);
$this->assertFalse($stub->save($this->input));
But this does not apply to the save method of the model.
I also tested (in sandbox mode) :
$this->mock = Mockery::mock(Illuminate\Database\Eloquent\Model::class);
$this->app->instance(Illuminate\Database\Eloquent\Model::class, $this->mock);
$this->mock
->shouldReceive('save')
->once()
->andReturn('foo');
dump($this->call('GET', '/api/articles'));
Thanks for help.
Please or to participate in this conversation.