DEV Community

Cover image for Laravel Unit Test Exceptions
Buddhi Eashwarage
Buddhi Eashwarage

Posted on • Originally published at theodddeveloper.com

Laravel Unit Test Exceptions

Let’s see how to unit test Exceptions in Laravel with PHPUnit. For that, I’m going to create a hypothetical scenario where there is a student class greets to new student, and it accepts 2 arguments. The first argument is a greeting such as “Hi”, “Hello”, and “Welcome”. And the second argument is the first name of the student such as “Tom”, “Andrew”, “Peter”, etc. So, we’re going to throw an exception here if the first argument for the greeting is not a desired one from our list.

I'm going to create a new "Student" class using PHP artisan.

create a new

So, it will appear in the VS Code as below.

appear in the VS Code
Let's add the logic there.

add the logic
In this logic, it accepts any greeting, but I need to restrict that only to several ones as mentioned earlier.

So, what I'm going to do here is to filter from our desired list, and throw an exception if the greeting is not in our list. I'm using the opposite of the Core PHP function in_array().

So the updated logic will be like this.

the updated logic

Let's try this from the tinker. If you like to test this from the browser, I have created a YouTube video for that. Please refer to that - YouTube video

In Laravel Tinker, we can simply test like below. And it's even thrown an exception as we expected!!

Laravel Tinker, we can simply test

Now let's try the most important part which is unit testing.

I'm creating a new unit test from an artisan command.

creating a new unit test

So, there is a fresh unit test created.

a fresh unit test created

Let's add the unit test for testing a successful operation first.

test for testing a successful operation

Cool, it's passing!!

it's passing

Let's add a test case for testing the exception.

But there's a trick in that test case.

We need to assert before calling the Student object's "greetStudent()" method.

Why is that? Because once an exception is thrown the method exits. Therefore, we need to prepare the unit test beforehand.

Let's see how it goes.

Let's see how it goes

The test case will be like the above.

If we swap the lines, like below it will fail due to the reason that I mentioned a while ago.

swap the lines

So, we need to carefully put the lines in the correct order.

The output after running the test cases is:

output after running the test cases

It's passing! Which means it threw an exception successfully!

Let's go ahead an another step.

We can write a unit test for the exact Exception message.

Let's try it out.

It's like this.

a unit test for the exact Exception message

It's also passing!

It's also passing

That's it!

Happy coding!

Top comments (0)