To test RESTful APIs and perform HTTP requests with PHPUnit, you can follow these steps:
Install PHPUnit: If you haven't already, install PHPUnit by following the official documentation.
Create a Test Class: Create a new test class by extending the PHPUnit\Framework\TestCase class.
use PHPUnit\Framework\TestCase;
class APITest extends TestCase
{
// Test methods will go here
}
protected function setUp(): void
{
// Set up any required resources
}
protected function tearDown(): void
{
// Clean up any created resources
}
public function testGetRequest()
{
$client = new GuzzleHttp\Client();
$response = $client->get('http://example.com/api');
$this->assertEquals(200, $response->getStatusCode());
$this->assertJson($response->getBody());
}
public function testPostRequest()
{
$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api', [
'json' => ['name' => 'John', 'age' => 25]
]);
$this->assertEquals(201, $response->getStatusCode());
$this->assertJson($response->getBody());
}
phpunit --bootstrap vendor/autoload.php path/to/testfile.php
Make sure to replace "vendor/autoload.php" with the correct path to the PHPUnit autoloader and "path/to/testfile.php" with the actual path to your test file.
Note: Remember to check the PHPUnit and Guzzle HTTP client documentation for more details on how to use their features and customize your tests according to your specific needs.