Courses

Testing in Laravel 11 For Beginners

Feature vs Unit Tests: The Difference

Summary of this lesson:
- Detailed comparison of Unit and Feature tests
- Creating Service class for currency conversion
- Writing Unit tests for specific functionality
- Guidelines for choosing between Feature and Unit tests

In this lesson, let's talk about Unit Tests versus Feature Tests.

A unit is some internal piece of code in your application: usually a function or a class. So, the purpose of Unit tests is to test precisely those units, without loading the full page routes or API endpoints.

Unit tests usually don't use the full feature but instead, test that some internal method returns correct data.

Let me show you a practical example.


New Feature: Service Class

For this example, we want to show additional prices in Euro in the table.

products table with eur price

To show the price in Euro, there is a converter. Imagine a CurrencyService class in the App\Services directory. In the service, there is a function to convert the price.

app/Services/CurrencyService.php:

namespace App\Services;
 
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);
}
}

For simplicity, we just fake the conversion rate as a constant. In the real world, of course, there will be...

The full lesson is only for Premium Members.
Want to access all 25 lessons of this course? (90 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord