44 lines
1.3 KiB
Markdown
44 lines
1.3 KiB
Markdown
---
|
|
title: >
|
|
Asserting all the things
|
|
pubDate: 2023-08-19
|
|
permalink: >-
|
|
archive/2023/08/19/asserting-all-the-things
|
|
tags:
|
|
- php
|
|
---
|
|
|
|
As well as assertions within tests, you can also check within implementation code that things are in an expected state or contain a certain value.
|
|
|
|
In PHP, this is done by throwing an Exception if a condition is met.
|
|
|
|
For example:
|
|
|
|
```language-php
|
|
if (!is_array(false)) {
|
|
throw new \Exception('Not an array');
|
|
}
|
|
```
|
|
|
|
There's also the `assert` construct which, since PHP 8.0, throws an Exception by default:
|
|
|
|
```language-php
|
|
assert(is_array(false));
|
|
```
|
|
|
|
You can also use an assertion library, such as `webmozart/assert` or `beberlei/assert` which provide assertions and guard methods:
|
|
|
|
```language-php
|
|
use Webmozart\Assert\Assert;
|
|
|
|
Assert::isArray(false);
|
|
```
|
|
|
|
Similarly, if the condition fails, it throws an Exception that can be caught elsewhere.
|
|
|
|
As well as basic assertions such as the item is the expected type or don't match the condition, there are more complex assertions, such as all items within an array are a certain type or that an integer is positive.
|
|
|
|
## Here's the thing
|
|
|
|
I use guard conditions a lot within my code. If something is not as I'd expect, I like for an error to be thrown. This makes is easy to test and to debug any failures compared to failing silently.
|