php-laravelHow do I write a unit test in Laravel using PHP?
Unit testing in Laravel with PHP is done using the PHPUnit testing framework. The first step is to install the package with the command composer require --dev phpunit/phpunit
.
Once installed, you can create a new test class by running the command php artisan make:test MyTest
. This will create a new test class in the tests/Unit
directory.
In the newly created test class, you can define the tests that you want to run. For example, the following test will check if the add
method of the Calculator
class returns the correct result:
<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\Calculator;
class CalculatorTest extends TestCase
{
public function testAdd()
{
$calculator = new Calculator;
$this->assertEquals(30, $calculator->add(10, 20));
}
}
The test can then be run from the command line using phpunit
. Upon successful completion, you should see the following output:
PHPUnit 7.5.20 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.006, Memory: 6.00 MB
OK (1 test, 1 assertion)
The code above consists of the following parts:
namespace Tests\Unit
- defines the namespace of the test classuse Tests\TestCase
- imports the TestCase class which provides the necessary setup for the testuse App\Calculator
- imports the Calculator class which is being testedpublic function testAdd()
- defines a test method which checks if theadd
method of theCalculator
class returns the correct result$calculator = new Calculator
- creates a new instance of theCalculator
class$this->assertEquals(30, $calculator->add(10, 20))
- checks if the result of theadd
method is equal to 30
For more information, see the PHPUnit Documentation and the Laravel Documentation.
More of Php Laravel
- How do I set up a Laravel worker using PHP?
- How do I run a seeder in Laravel using PHP?
- How can I use the @yield directive in PHP Laravel?
- ¿Cómo configurar PHP y Laravel desde cero?
- How can I use React with PHP Laravel?
- How can I use PHP Laravel to create a Wikipedia page?
- How can I use PHP Laravel's ZipArchive library to create a zip file?
- How can I use PHP and Laravel together?
- How can I get the current year in PHP Laravel?
- How do I decide between using PHP Laravel and Yii for my software development project?
See more codes...