Skip to content

Instantly share code, notes, and snippets.

@markheramis
Last active September 27, 2024 20:06
Show Gist options
  • Select an option

  • Save markheramis/27c2a14e3d0d5af67f4cb7d19600a2f8 to your computer and use it in GitHub Desktop.

Select an option

Save markheramis/27c2a14e3d0d5af67f4cb7d19600a2f8 to your computer and use it in GitHub Desktop.
Ghost Routes for Testing

Temporary API Testing in Laravel

This section describes the setup and testing of a temporary API route within a PHPUnit test case in a Laravel application.

Overview

The provided snippet demonstrates how to dynamically add a route within the setUp method of a PHPUnit test case and test the API response.

Code Description

  • setUp Method:

    • The setUp method is overridden to set up the test environment.
    • It calls the parent setUp method.
    • A POST route /test is dynamically added. This route accepts a request, adds two parameters (a and b), and returns the result in a JSON response.
  • testAdditionResponse Method:

    • This method tests the temporary API route.
    • It sends a POST request to the /test route with parameters a and b.
    • It asserts that the response status is 200 and that the JSON response contains the expected result of the addition.

Usage

  1. Copy TemporaryApiTest.php to your Laravel Project's tests/Unit directory.
  2. Run the Test: To execute the test, run the following command in your terminal: php artisan test --filter=TemporaryApiTest
  3. Expected Output: The test will verify that the /test route correctly adds the numbers provided in the request and returns the expected result.

Conclusion

This example demonstrates how to dynamically create routes within PHPUnit tests, providing a flexible way to test API endpoints without permanent modifications to the route files.

<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Http\Request;
class TemporaryApiTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
// Dynamically add routes
\Route::post('/test', function (Request $request) {
$result = $request->a + $request->b;
return response()->json(['result' => $result]);
});
}
public function testAdditionResponse() {
$response = $this->postJson('/test', ['a' => 1, 'b' => 2]);
$response->assertStatus(200)
->assertJson(['result' => 3]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment