Testing is crucial in every application, especially if that application needs to be maintained. So, in this lesson, let's see how we can test APIs.
Before creating a test for the API, let's quickly set up our application.
It is crucial to run tests on a separate database from your main one, because it wipes and re-creates the database with every test. The easiest way is to uncomment two lines in the phpunit.xml
file, then your tests will run on an in-memory SQLite database.
phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?><phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true"> <testsuites> <testsuite name="Unit"> <directory>tests/Unit</directory> </testsuite> <testsuite name="Feature"> <directory>tests/Feature</directory> </testsuite> </testsuites> <source> <include> <directory>app</directory> </include> </source> <php> <env name="APP_ENV" value="testing"/> <env name="APP_MAINTENANCE_DRIVER" value="file"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_STORE" value="array"/> <!-- <env name="DB_CONNECTION" value="sqlite"/> --> <!-- <env name="DB_DATABASE" value=":memory:"/> --> <env name="MAIL_MAILER" value="array"/> <env name="PULSE_ENABLED" value="false"/> <env name="QUEUE_CONNECTION" value="sync"/> <env name="SESSION_DRIVER" value="array"/> <env name="TELESCOPE_ENABLED" value="false"/> </php></phpunit>
Next, you must know that every test class must have Illuminate\Foundation\Testing\RefreshDatabase
trait to create tables. Without this trait, you will get the error message no such table:
.
Now, let's create a test class.
php artisan make:test Api/CategoryTest
Similar to Controllers, we create tests inside...