Negative CRUD Unit Testing in Laravel 5

Jeff Simons Decena
2 min readMar 7, 2018

--

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

PHPUnit 6.5.7 by Sebastian Bergmann and contributors..                                                                   1 / 1 (100%)Time: 993 ms, Memory: 26.00MBOK (1 test, 1 assertion)

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.

PHPUnit 6.5.7 by Sebastian Bergmann and contributors..                                                                   1 / 1 (100%)Time: 936 ms, Memory: 26.00MBOK (1 test, 1 assertion)

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!

PHPUnit 6.5.7 by Sebastian Bergmann and contributors..                                                                   1 / 1 (100%)Time: 969 ms, Memory: 26.00MBOK (1 test, 1 assertion)

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

➜  git: phpunit --filter=CarouselUnitTest::it_error_when_deleting_a_non_existing_carousel
PHPUnit 6.5.7 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)Time: 938 ms, Memory: 26.00MBOK (1 test, 1 assertion)

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

###

/jsd

--

--

Jeff Simons Decena

Senior Fullstack Engineer, React Native developer and HL7 Health Informatics professional