Testing on delete action - Coverage on unsuccessful delete

Hi,

I’m creating testing for my application, but I keep getting stumped on the delete actions. I can assert that the entity is deleted and thus get coverage for that part. I can’t, however, get coverage for the unsuccessful deletion of entity, as I can’t think of any way to attempt to delete something that won’t be deleted. The delete method provided below is standard from Cake Bake

My code in FilesController.php

/**
 * Delete method
 *
 * @param string|null $id File id.
 * @return \Cake\Http\Response|null Redirects to index.
 * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
 */
public function delete($id = null)
{
	$this->getRequest()->allowMethod(['post', 'delete']);
	$file = $this->Files->get($id);
	if ($this->Files->delete($file)) {
		$this->Flash->success(__('The file has been deleted.'));
	} else {
		$this->Flash->error(__('The file could not be deleted. Please, try again.'));
	}

	return $this->redirect(['action' => 'index']);
}

As you can see in the image below, most of the method is green, meaning it has coverage. The red part lacks coverage, as per the issue above. Do any of you have an idea how I can get coverage for the last part, by requesting to delete an entity not fit for deletion?

image

Mock the model with https://book.cakephp.org/3.0/en/development/testing.html#mocking-model-methods and return false on the call to delete.

Thanks, Schlaefer, that really did the trick. I have read that section when wanting to test for emails, but didn’t consider it for this use case.

Code that worked for me:

$model = $this->getMockForModel('Files', ['delete']);
$model->expects($this->once())
	->method('delete')
	->will($this->returnValue(false));
$this->delete(['controller' => 'files', 'action' => 'delete', 1]);
$this->assertRedirect(['controller' => 'files', 'action' => 'index']);
$this->assertSession(__('The file could not be deleted. Please, try again.'), 'Flash.flash.0.message');