In this article, we will show an example of PHP Unittest in Laravel framework, include unit test and exception test.
At first, create fellowing controller, test and exception by artisan make.
And in here we also generate a service:
php artisan make:controller weatherController
php artisan make:controller ../Services/weatherServices
php artisan make:test weatherServicesTest
php artisan make:exception WeatherNotFoundException
And now, you can see the following code for knowing how it worked.
WeatherNotFoundException
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Support\Facades\Log;
class WeatherNotFoundException extends Exception
{
/**
* Report or log an exception.
*
* @return void
*/
public function report()
{
Log::debug($this->getMessage());
}
}
WeatherServices.php (first you should change namespace to corrected)
<?php
namespace App\Http\Services;
use Illuminate\Http\Request;
use App\Exceptions\WeatherNotFoundException;
class WeatherServices
{
protected $users;
public function __construct(string $users = '')
{
$this->users = $users;
}
/**
* Get weather info
*
* @return array
*/
public function getWeather($name='')
{
if ($name!='') {
$this->users = $name;
}
if ($this->users == '') {
throw new WeatherNotFoundException('please input user name');
}
return ['weather'=>'rain', 'user'=>$this->users];
}
}
weatherController
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Services\WeatherServices;
use App\Exceptions\WeatherNotFoundException;
class weatherController extends Controller
{
protected $users = 'default from controller';
protected $WeatherServices;
public function __construct(WeatherServices $WeatherServices)
{
$this->WeatherServices = $WeatherServices;
}
/**
* current weather
*
* @return void
*/
public function currentWeather($name = '')
{
if($name!=''){
$this->users = $name;
}
try {
$results = $this->WeatherServices->getWeather($this->users);
} catch (WeatherNotFoundException $e) {
report($e);
return false;
}
return $results;
}
}
weatherServicesTest.php
<?php
namespace Tests\Feature;
use Mockery;
use Tests\TestCase;
use Mockery\MockInterface;
use App\Http\Services\WeatherServices;
use App\Exceptions\WeatherNotFoundException;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class WeatherServiceTest extends TestCase
{
/**
* Test weather should get expection when no input name
*
* @return void
*/
public function testWeatherShouldGetExpectionWhenNoInputName()
{
$this->expectException(WeatherNotFoundException::class);
$this->expectExceptionMessage('please input user name');
$WeatherServices = new WeatherServices('');
$WeatherServices->getWeather();
}
}