Chapter 3: Setting Expectations with PestPHP - Unleashing the Power of Assertions
In this chapter, we'll delve into the PestPHP expectation API, a powerful tool for setting expectations in your tests. By expressing clear expectations about your code's behavior, you can effortlessly pinpoint bugs and identify issues during testing.
The Power of Expectations
In testing, expectations serve as the criteria against which your code's output is evaluated. PestPHP provides a clean and expressive expectation API that makes it easy to define what you anticipate from your code.
Basic Expectations
Let's start with the basics. You can use the expect
function to create expectations about the outcome of your code:
it('should add two numbers')
->expect(1 + 1)->toBe(2);
In this example, the expectation is that the result of adding 1 and 1 should be equal to 2. If the expectation fails, PestPHP will clearly indicate what was expected versus what was received.
Chaining Expectations
PestPHP allows you to chain multiple expectations together, making it easy to express complex conditions in a readable manner:
it('should validate a user')
->expect($user->isActive())->toBeTrue()
->and($user->isAdmin())->toBeFalse();
Here, we're chaining expectations to validate that a user is active and not an admin. If any part of the expectation chain fails, PestPHP will provide detailed information about the failure.
Negating Expectations
Sometimes, you may want to express the negation of an expectation. PestPHP makes this straightforward:
it('should check for inequality')
->expect(1 + 1)->not->toBe(3);
In this case, the expectation is that 1 + 1 should not be equal to 3. The not
modifier negates the expectation, providing a clear way to express inequality.
Advanced Expectations
PestPHP supports a wide range of advanced expectations, including:
Type Assertions:
it('should assert the type') ->expect($result)->toBeInstanceOf(MyClass::class);
Array Assertions:
it('should assert array values') ->expect($array)->toContain('value');
String Assertions:
it('should assert string content') ->expect($string)->toContain('substring');
Exception Assertions:
it('should assert an exception') ->expect(fn() => $this->myMethod())->toThrow(MyException::class);
For more about expectations expectations
Conclusion
By using the PestPHP expectation API, you can clearly define the expected behavior of your code and effortlessly identify issues during testing. Whether you're validating basic arithmetic or asserting complex conditions, PestPHP's expressive syntax and powerful features make it a valuable tool for setting expectations in your tests. In the next chapter, we will explore strategies for handling edge cases and exceptional scenarios in your PestPHP tests.