Getting Started with Unit Testing in Laravel
- 2023年11月21日
- 技術情報
Unit testing is a crucial aspect of any robust software development process. In Laravel, a popular PHP framework, writing unit tests is not only easy but also highly encouraged. In this tutorial, we will go through the basics of writing unit tests in Laravel, ensuring the reliability and stability of the individual code units.
Prerequisites
Before diving into writing unit tests, make sure the following prerequisites be installed:
1. Composer
2. Laravel Installed
3. PHPUnit
Setting Up a Laravel Project
Use the following commands to set up a new project:
composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app
Creating a Unit Test
Laravel provides a convenient Artisan command to generate a test class. Let’s create a simple unit test for a hypothetical `Calculator` class:
php artisan make:test CalculatorTest --unit
This will generate a test file located at `tests/Unit/CalculatorTest.php`. Open the file and you’ll see a basic test structure.
Writing a Unit Test
Now, let’s write a unit test for a basic addition method in our `Calculator` class. Open `CalculatorTest.php` and modify it as follows:
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\Calculator;
class CalculatorTest extends TestCase
{
public function testAddition()
{
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result);
}
}
In this example, assume we have a `Calculator` class in the `app` directory with an `add` method like that.
namespace App;
class Calculator
{
public function add($a, $b)
{
return $a + $b;
}
}
Running Unit Tests
To run the unit tests, use the following command:
php artisan test
This will execute all the tests in the `tests` directory.
Assertions
Laravel provides a variety of assertions that can be used in the tests. In this example, we used `assertEquals` to verify that the addition method returns the expected result. Explore other assertions and details in the official documentation https://laravel.com/docs/10.x/testing.
Conclusion
We’ve just written a first unit test in Laravel. As the application grows, writing tests for individual code units will become an integral part of the development process, ensuring that the code remains maintainable and reliable. Hope you enjoy that.
Asahi
waithaw at 2023年11月21日 10:00:00