Negative CRUD Unit Testing in Laravel 5

As part II of the CRUD Unit Testing in Laravel 5, we continue with negative testing.

What we have in the previous article is testing the positive side; say it CAN create, update, show or delete the carousel we are trying to do.

Now let us test the opposite, what if it fails and how we handle it?

Let us start on the CREATE test.

Remember, when we create our migration file,

we set the link as nullable but the title and the src are NOT NULL.

So, we expect here that the database should throw an error when those columns are null right? Good thing we are catching it in our repository class!

Look, in Laravel, the database error is QueryException so we catch it and create our own more readable error exception CreateCarouselErrorException

With these things in place, run your phpunit and see what happens

Nice job.

This means we are catching it correctly.

Later, we can catch this CreateCarouselErrorException in our controller and respond with our own action when we hit it.

How about when the carousel is not found?

And looking back at our findCarousel() method in our repository

We are catching the ModelNotFoundException which is default to Laravel when it can’t find the model. Good!

Now, run phpunit again.

Getting a hold of it? Good.

How about when we cannot update it?

You see, we purposely set the title to null because in our previous test it will throw an error if this is null when created. So we assume that the title has a value in the database already.

Note: When expecting for the error, it should always be on top of the method we are trying to test

And the updateCarousel() method

Run phpunit!

Great dude!

Next is delete. But we have to modify our return type from bool to ?bool which means it can boolean or null

Important: You must be running on ≥ php 7.1 to get this feature

Then the test

And the result

Now the negative unit testing is complete! How have you been in this journey? Constructive comment is welcome!



Senior Fullstack Engineer