Backend Testing - shibotsu/obs-clone GitHub Wiki
📘 Feature Testing in Laravel Using PHPUnit
Feature testing in Laravel allows you to test your application's endpoints and features as a whole, simulating real user interactions. Laravel uses PHPUnit as its default testing framework.
Getting Started
-
Install Dependencies
Make sure PHPUnit is installed (Laravel includes it by default). -
Test Directory
Feature tests are stored in thetests/Feature
directory.
Creating a Feature Test
Generate a new feature test using Artisan:
php artisan make:test ExampleFeatureTest
This creates a file in tests/Feature
.
Writing a Feature Test
Example: Testing a route returns a successful response.
public function test_homepage_displays_correctly()
{
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Welcome');
}
Common Assertions
assertStatus($code)
– Check HTTP status code.assertSee($text)
– Check if response contains text.assertJson($array)
– Check if response contains JSON fragment.assertRedirect($url)
– Check for redirects.
Testing with Authentication
Laravel provides helpers to act as users:
public function test_authenticated_user_can_access_dashboard()
{
$user = User::factory()->create();
$response = $this->actingAs($user)->get('/dashboard');
$response->assertStatus(200);
}
Running Feature Tests
Run all tests:
php artisan test
Or only feature tests:
php artisan test --testsuite=Feature
Best Practices
- Use factories to create test data.
- Clean up after tests using database transactions.
- Name tests clearly to describe their purpose.
For more details, see the Laravel Testing documentation.
Project testing
In this project, we implemented over 50 feature tests to ensure the reliability of our API endpoints. The tests primarily utilized the assertStatus
and assertJson
assertions, as Laravel was used to build a RESTful API.
Key areas covered by the tests include:
- User authentication (login and registration)
- Following and unfollowing users
- Updating user data
These tests help guarantee that core functionalities work as expected and that the API responds correctly to various requests.