Unit test with mockery on Laravel
Sep 5, 2020
PHP
PHPUnit
mockery
laravel5
What you can do by reading this article
You will be able to do Unit Test using Mockery in Laravel.
- Since it was made quite a while ago, please feel free to point out mm
What is Mockery in the first place?
A PHP mock object framework that makes it easy to create mock with PHPUnit. https://readouble.com/mockery/1.0/ja/index.html
#Environment laravel 5.3 phpunit 5.7.3 Use mockery
Thing you want to do
- -I want to Mock an unimplemented static method called Test :: getInfo () and test it with phpunit.
- -I want to confirm at the same time through validation of laravel by sending post
The existing laravel validation is done in the store (IdRequest $ request) part of the code below. I’m doing a POST using $ this-> call () to test here. The situation that Test :: getInfo (), which is a part of the series of processing, is not implemented by external connection.
#Procedure
1. Routing settings
Route :: resource ('info','info @ store');
2. $ this-> call Controller call
<? php
namespace App \ Http \ Controllers;
use Illuminate \ Http \ Request;
use App \ Http \ Controllers \ Controller;
use App \ Http \ Requests \ Rlog \ IdRequest;
use App \ Http \ Models \ InfoLogic;
class InfoController extends Controller {
public function store (IdRequest $ request) {
$ info = new InfoLogic ($ request)
$ info-> setInfo ();
return $ info-> getInfo ();
}
}
3. Validate with IdRequest
<? php
namespace App \ Http \ Requests;
use Illuminate \ Foundation \ Http \ FormRequest;
use Illuminate \ Contracts \ Validation \ Validator;
class IdRequest extends FormRequest
{
public function authorize ()
{
return true;
}
public function rules ()
{
return [
'id' =>' required | max: 255 | alpha_num',
];;
}
}
4. Calling information from Model associated with ID
<? php
namespace App \ Models;
use Illuminate \ Database \ Eloquent \ Model;
class Infologic extends Model {
public function __construct ($ request) {
$ this-> id = $ request ['id'];
}
public function setInfo () {
$ this-> info = Test :: getInfo ($ this-> id);
}
public function getInfo () {
return $ this-> info;
}
}
5. Call information from DB (Test :: getInfo ($ this-> id);, not implemented)
Mock this part.
6. Write test code based on the above
<? php
use Mockery as m;
use App \ Models \ InfoLogic;
class InfoValidateTest extends TestCase
{
public function tearDown ()
{
parent :: tearDown ();
m :: close ();
}
/ **
* @runInSeparateProcess
* /
public function test_id_name ()
{
// Create mock to get id
$ mocker = m :: mock ('alias: App \ Models \ Test');
$ return = 123456;
$ argument ='yamada';
$ mocker-> shouldReceive ('getInfo')-> andReturn ($ return);
$ expected = 123456;
$ actual = $ this-> call ('POST','info', array ('id' =>'tanaka'));
$ this-> assertEquals ($ expected, $ actual);
}
}
7. Test command execution
$ cd [Laravel project]
$ ./vendor/bin/phpunit tests / InfoValidateTest.php