Reputation: 25
I am writing tests in Laravel. However, I am in trouble because I do not know how to test. There is a method to make an http request as shown below. How would you typically test this method? Should I use a URL or mock that is actually accessible?
PHP 7.4.6 Laravel 7.0
<?php
namespace App\Model;
use Illuminate\Support\Facades\Http;
use Exception;
class Hoge
{
public function getText(string $url, ?string $user, ?string $password, string $ua): bool
{
$header = ["User-Agent" => $ua];
$httpObject = $user && $password ? Http::withBasicAuth($user, $password)->withHeaders($header) : Http::withHeaders($header);
try {
$response = $httpObject->get($url);
if ($response->ok()) {
return $response->body();
}
} catch (Exception $e) {
return false;
}
return false;
}
}
Upvotes: 1
Views: 2877
Reputation: 1844
Functionality that reaches out to other systems can be slow and make tests brittle. Nevertheless, you want to be sure that your getText
method works as expected. I would do the following:
Create a set of integration tests just for your getText
method. These tests make actual http requests to a server to verify the expected behaviors. The web server don't have to be an external system. You could use php's built in webserver to provide test urls. You can find an article here that guides you in that direction.
For every other functionality that uses the getText
method, I'd mock that method to keep the tests fast.
Upvotes: 1
Reputation: 3420
To create a new test case, you can use the make:test
Artisan command:
php artisan make:test HogeTest
Then you can create your HogeTest, considering your headers are correct
<?php
namespace Tests\Feature;
use Tests\TestCase;
class HogeTest extends TestCase
{
public function hogeExample()
{
$header = ["User-Agent" => $ua];
$response = $this->withHeaders([
$header,
])->json('POST', $url, ['username' => $user, 'password' => $password]);
$response->assertStatus(200);
// you can even dump response
$response->dump();
}
}
This is a simple example how you can use modify it as per your need. See more in laravel docs
Upvotes: 1
Reputation: 594
I prefer Postman for web server / API testing. https://www.postman.com/downloads/
Upvotes: 0