Last active
September 8, 2022 09:45
-
-
Save DominikStyp/afaafec093c5e1558bc165326ffcd154 to your computer and use it in GitHub Desktop.
Laravel testing using built-in Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Tests\TestCase; | |
use App\Rules\BSNRule; | |
class SomeTest extends TestCase | |
{ | |
public function testMe() | |
{ | |
$data = [ | |
'productCode' => 10, | |
'bsn' => 'US12312312312321', | |
]; | |
$this->assertArrayDataMatchesValidationRules([ | |
'productCode' => 'required|string|min:1|max:10', | |
'bsn' => ['required', new BSNRule()], | |
], $data); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use Illuminate\Support\Facades\App; | |
use Illuminate\Validation\ValidationException; | |
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Facades\Validator; | |
/** | |
* Class TestCase | |
*/ | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication; | |
/** | |
* @param array $keys | |
* @param array $arr | |
*/ | |
protected function assertArrayHasKeys(array $keys, array $arr): void | |
{ | |
foreach($keys as $k){ | |
$this->assertArrayHasKey($k, $arr); | |
} | |
} | |
/** | |
* @param array $validationRules - ex. ['last_name' => 'required|min:6|max:100'] | |
* @param array $inputData - ex. ['last_name' => 'John'] | |
*/ | |
protected function assertArrayDataMatchesValidationRules(array $validationRules, array $inputData): void | |
{ | |
$defaultLocale = App::getLocale(); | |
App::setLocale('en'); | |
$validator = Validator::make( | |
Arr::only($inputData, array_keys($validationRules)), | |
$validationRules | |
); | |
try { | |
$validator->validate(); | |
} catch (ValidationException $exception){ | |
dump($validator->invalid(), $validator->errors()); | |
throw $exception; | |
} finally { | |
// in case you need default locale in further testing | |
App::setLocale($defaultLocale); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment