Skip to main content

Unit-Testing APIs and JSONs

Premium
5:21

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 33 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.