daily-email: add 2023-08-19
Asserting all the things
This commit is contained in:
parent
0caf486d4e
commit
35b3e291ba
43
src/content/daily-email/2023-08-19.md
Normal file
43
src/content/daily-email/2023-08-19.md
Normal file
|
@ -0,0 +1,43 @@
|
|||
---
|
||||
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:
|
||||
|
||||
```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:
|
||||
|
||||
```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:
|
||||
|
||||
```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.
|
Loading…
Reference in a new issue