Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Sometimes code throws an exception when not used properly. PHPUnit gives us way to test for that output as well.
NOTE
In namespaced context the Exception class needs to be prefixed with global prefix operator. If you get a failure message when trying to use an InvalidArgumentException, add a slash before the exception to make sure you are using the exception from the global namespace: \InvalidArgumentException
Testing Exceptions
PHPUnit Exception Documentation
Tips
- Excepted exceptions are written BEFORE the code expected to throw the exception.
- If you're having problems with
InvalidArgumentException
you can try calling the base implementation of that exception by using the global namespace (a \ before the exception).\InvalidArgumentException
Example:
/** @test */
function addIngredientMustReceiveValidAmount()
{
$this->expectException(\InvalidArgumentException::class);
$recipe = new Recipe();
$recipe->addIngredient("garlic", "two");
}
From our Code Coverage, report we can see
that we should be getting an exception on
0:00
our addIngredient method if we don't enter
a valid amount or a valid measurement.
0:05
Let's add tests for these exceptions.
0:13
Since we don't need a full recipe for
these tests,
0:17
I'm going to add them to
my RecipesTest.php file.
0:20
Our test be function
0:26
addIngredientMustReceiveValidAmount.
0:30
For this test, I'm just going to check for
a valid exception.
0:41
When testing for exceptions,
we add our expected exception first,
0:46
$this->expectException(InvalidArgumentExc-
eption::class).
0:52
Then we'll add our recipe.
1:01
And the code we expect to throw
the exception, $recipe->addIngredient.
1:06
We'll add garlic with the word two,
let's run this test.
1:14
Great, let's add our next exception.
1:22
Function
addIngredientMustReceiveValidMeasurement.
1:30
And this time, for the expected exception,
we're going to check a message.
1:42
We'll start with a blank message,
and then we'll start $recipe.
1:50
= new Recipe(), and
1:57
then $recipe->addIngredient("garlic"), 2.
2:00
And this time an invalid "tbl" for
tablespoon, now let's run our test.
2:08
As expected we get the error.
2:17
But now we can copy and
paste this message.
2:18
Great, run the test again,
and it all passes.
2:29
Let's refresh our Code Coverage report.
2:35
You need to sign up for Treehouse in order to download course files.
Sign up