CpfTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Tests\Unit\ValueObjects;
  3. use App\Models\Franchisee;
  4. use App\Models\StudentResponsible;
  5. use App\Models\UnitPartner;
  6. use App\Models\User;
  7. use App\ValueObjects\Cpf;
  8. use Illuminate\Support\Facades\Validator;
  9. use InvalidArgumentException;
  10. use Tests\TestCase;
  11. class CpfTest extends TestCase
  12. {
  13. public function test_it_accepts_and_normalizes_a_valid_cpf(): void
  14. {
  15. $cpf = new Cpf('529.982.247-25');
  16. $this->assertSame('52998224725', $cpf->value());
  17. $this->assertSame('529.982.247-25', $cpf->formatted());
  18. $this->assertSame('52998224725', (string) $cpf);
  19. $this->assertSame('"52998224725"', json_encode($cpf));
  20. }
  21. public function test_it_rejects_an_invalid_cpf(): void
  22. {
  23. app()->setLocale('pt');
  24. $this->expectException(InvalidArgumentException::class);
  25. $this->expectExceptionMessage('O CPF informado é inválido.');
  26. new Cpf('111.111.111-11');
  27. }
  28. public function test_its_request_rule_validates_cpf(): void
  29. {
  30. $valid = Validator::make(
  31. ['cpf' => '529.982.247-25'],
  32. ['cpf' => ['required', Cpf::rule()]],
  33. );
  34. $invalid = Validator::make(
  35. ['cpf' => '529.982.247-24'],
  36. ['cpf' => ['required', Cpf::rule()]],
  37. );
  38. $this->assertTrue($valid->passes());
  39. $this->assertTrue($invalid->fails());
  40. }
  41. public function test_its_request_rule_uses_the_current_locale(): void
  42. {
  43. app()->setLocale('es');
  44. $validator = Validator::make(
  45. ['cpf' => '529.982.247-24'],
  46. ['cpf' => [Cpf::rule()]],
  47. );
  48. $this->assertSame(
  49. 'El CPF proporcionado no es válido.',
  50. $validator->errors()->first('cpf'),
  51. );
  52. }
  53. public function test_models_cast_cpf_to_the_value_object(): void
  54. {
  55. foreach ([Franchisee::class, StudentResponsible::class, UnitPartner::class, User::class] as $modelClass) {
  56. $model = new $modelClass;
  57. $model->cpf = '529.982.247-25';
  58. $this->assertInstanceOf(Cpf::class, $model->cpf);
  59. $this->assertSame('52998224725', $model->getAttributes()['cpf']);
  60. }
  61. }
  62. }