CnpjTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Tests\Unit\ValueObjects;
  3. use App\Models\Franchisee;
  4. use App\Models\Unit;
  5. use App\ValueObjects\Cnpj;
  6. use Illuminate\Support\Facades\Validator;
  7. use InvalidArgumentException;
  8. use Tests\TestCase;
  9. class CnpjTest extends TestCase
  10. {
  11. public function test_it_accepts_and_normalizes_a_numeric_cnpj(): void
  12. {
  13. $cnpj = new Cnpj('04.252.011/0001-10');
  14. $this->assertSame('04252011000110', $cnpj->value());
  15. $this->assertSame('04.252.011/0001-10', $cnpj->formatted());
  16. $this->assertSame('04252011000110', (string) $cnpj);
  17. $this->assertSame('"04252011000110"', json_encode($cnpj));
  18. }
  19. public function test_it_accepts_and_normalizes_an_alphanumeric_cnpj(): void
  20. {
  21. $cnpj = new Cnpj('12.abc.345/01de-35');
  22. $this->assertSame('12ABC34501DE35', $cnpj->value());
  23. $this->assertSame('12.ABC.345/01DE-35', $cnpj->formatted());
  24. }
  25. public function test_it_rejects_an_invalid_cnpj(): void
  26. {
  27. app()->setLocale('pt');
  28. $this->expectException(InvalidArgumentException::class);
  29. $this->expectExceptionMessage('O CNPJ informado é inválido.');
  30. new Cnpj('04.252.011/0001-11');
  31. }
  32. public function test_its_request_rule_validates_cnpj(): void
  33. {
  34. $valid = Validator::make(
  35. ['cnpj' => '12.ABC.345/01DE-35'],
  36. ['cnpj' => ['required', Cnpj::rule()]],
  37. );
  38. $invalid = Validator::make(
  39. ['cnpj' => '12.ABC.345/01DE-36'],
  40. ['cnpj' => ['required', Cnpj::rule()]],
  41. );
  42. $this->assertTrue($valid->passes());
  43. $this->assertTrue($invalid->fails());
  44. }
  45. public function test_its_request_rule_uses_the_current_locale(): void
  46. {
  47. app()->setLocale('es');
  48. $validator = Validator::make(
  49. ['cnpj' => '04.252.011/0001-11'],
  50. ['cnpj' => [Cnpj::rule()]],
  51. );
  52. $this->assertSame(
  53. 'El CNPJ proporcionado no es válido.',
  54. $validator->errors()->first('cnpj'),
  55. );
  56. }
  57. public function test_models_cast_cnpj_to_the_value_object(): void
  58. {
  59. foreach ([Franchisee::class, Unit::class] as $modelClass) {
  60. $model = new $modelClass;
  61. $model->cnpj = '04.252.011/0001-10';
  62. $this->assertInstanceOf(Cnpj::class, $model->cnpj);
  63. $this->assertSame('04252011000110', $model->getAttributes()['cnpj']);
  64. }
  65. }
  66. }