This lesson is a "quick tip" to emphasize that you need to pick the proper assertion to get the correct assertion error.
For example, we have a simple Service for converting currencies.
app/Services/CurrencyService.php:
class CurrencyService{ const RATES = [ 'usd' => [ 'eur' => 0.98 ], ]; public function convert(float $amount, string $currencyFrom, string $currencyTo): float { $rate = self::RATES[$currencyFrom][$currencyTo] ?? 0; return round($amount * $rate, 2); }}
Then, in the unit test, we expect the converted value to be equal to some number from the result.
use App\Services\CurrencyService; test('convert usd to eur successful', function () { $convertedCurrency = (new CurrencyService())->convert(100, 'usd', 'eur'); expect($convertedCurrency) ->toBeFloat() ->toEqual(98.0);});
However, you could have the expected variable equal to something and use toBeTrue()
instead of toEqual()
.
Let's take a look at different error messages. One of them will be readable and clear.
So, after changing the expected value in the unit test:
use App\Services\CurrencyService; test('convert usd to eur successful', function () { $convertedCurrency = (new CurrencyService())->convert(100, 'usd', 'eur'); expect($convertedCurrency) ->toBeFloat() ->toEqual(97.0); });
If this test fails, the error message when is very clear: One value does not match another.
Here's an example if you use toBeTrue()
instead of toEqual()
.
use App\Services\CurrencyService; test('convert usd to eur successful', function () { $convertedCurrency = (new CurrencyService())->convert(100, 'usd', 'eur'); expect($convertedCurrency == 97.0) ->toBeTrue();});
Now, the error message needs to be clarified. What is false
, and what is true
here?
Generally, when working with assertions, try to pick the assertion that is the closest to what you're actually testing.
Use true
or false
assertions only as a last resort if you don't have any other assertions available.